adding to my arraylist with out overriding it in vb - vb.net

i just asked a question and i modified my my code accordingly. Something is very wrong with the way im writting my page load. my aim is to initialize the array only the first time and then to keep on incrementing it. can you help?
This is the code I used:
Imports AjaxControlToolkit
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class Shtick
Inherits System.Web.UI.Page
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
Dim ItemSelect As New ArrayList()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If ItemSelect.Count > 0 Then
ItemSelect = New ArrayList()
Session("itemInCart") = ItemSelect
End If
If Not IsPostBack Then
FillShtickList()
End If
End Sub
Protected Sub FillShtickList()
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection)
comm = New SqlCommand("SELECT RTRIM(ProductPrice) AS Price, ProductName, ProductImage, ProductID, ProductDescription FROM Products", conn)
Try
conn.Open()
reader = comm.ExecuteReader()
ShtickDataList.DataSource = reader
ShtickDataList.DataBind()
reader.Close()
Finally
conn.Close()
End Try
End Sub
'Protected Sub ShtickDataList_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ShtickDataList.ItemCreated
' 'If e.Item.ItemType = ListItemType.Item Then
' ' Dim pce As ModalPopupExtender = e.Item.FindControl("PopupControlExtender1")
' ' Dim behaviorID As String
' ' behaviorID = "pce_" & e.Item.DataItemIndex
' ' pce.BehaviorID = behaviorID
' ' Dim img As Image = e.Item.FindControl("PI")
'item select = which item was selected
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer
Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand
If e.CommandName = "ViewCart" Then
Response.Redirect("~/ShoppingCart.aspx")
End If
If e.CommandName = "addToCart" Then
Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
itemQtyOrdered = itemQuantity.SelectedValue
ItemSelect.Add(e.CommandArgument)
Quantities.Add(itemQtyOrdered)
Session("itemInCart") = ItemSelect
Session("quantities") = Quantities
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
'Dim i As Integer
'For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = (ItemSelected.Count - 1)
'Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelected.Count & ")"
Finally
conn.Close()
End Try
End Sub
End Class
End Try
End Sub
End Class
= CType(Session("itemInCart"), ArrayList)
'al.Add(SS)
'Session.Add("itemInCart", al)
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
'Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
'Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
Dim i As Integer
For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = ItemSelect(i)
Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
Finally
conn.Close()
End Try
End Sub
End Class
M(ProductPrice) AS Price, ProductID, ProductName FROM Products WHERE ProductID = #ProductID", conn)
comm = New SqlCommand("Insert into orders (UserID, ProductID, quantity) values (1, #ProductID, #Quantity)", conn)
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = item
comm.Parameters.Add("#Quantity", Data.SqlDbType.Int)
comm.Parameters("#Quantity").Value = qty
'Dim i As Integer
'For i = 0 To ItemSelect.Length - 1
' comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
' comm.Parameters("#ProductID").Value = ItemSelect(i)
'Next
Try
conn.Open()
comm.ExecuteNonQuery()
'reader = comm.ExecuteReader()
'ShoppingList.DataSource = reader
'ShoppingList.DataBind()
'reader.Close()
Finally
conn.Close()
End Try
End Sub

In the code:
If ItemSelect.Count > 0 Then
ItemSelect = New ArrayList()
Session("itemInCart") = ItemSelect
End If
You have a more than where you should have a less than. The arraylist only initialises when there is an item in the array. So you only initialise the array after it is initialised. WHat you need is:
If ItemSelect.Count > 0 Then
ItemSelect = New ArrayList()
Session("itemInCart") = ItemSelect
End If

Related

VB Net - How to get cascading drop down list to select self insert row without error?

I have 4 dropdownlist in my web form that is cascading, the value of the 1st dropdownlist will affect the selection of the 2nd dropdownlist and so on.
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString())
FillProcess(level1_ID)
End Sub
Protected Sub ddlprocess_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level2_ID As Integer = Convert.ToInt32(ddlprocess.SelectedValue.ToString())
FillEquipment(level2_ID)
End Sub
Protected Sub equipment_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level3_ID As Integer = Convert.ToInt32(equipment.SelectedValue.ToString())
FillStep(level3_ID)
End Sub
Private Sub FillLine() '1st dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level1_id, [LCODE1]+ ' | '+[LNAME1] as [LCODE1]" _
& " FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP]"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
line.DataSource = dt
line.DataTextField = "LCODE1"
line.DataValueField = "level1_id"
line.DataBind()
line.Items.Insert(0, "")
End If
End Sub
Private Sub FillProcess(ByVal level1_ID As Integer) '2nd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level2_id, [LCODE2]+ ' | '+[LNAME2] as [LCODE2] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level1_id = #level1_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level1_id", SqlDbType.Int).Value = level1_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
ddlprocess.DataSource = dt
ddlprocess.DataTextField = "LCODE2"
ddlprocess.DataValueField = "level2_id"
ddlprocess.DataBind()
ddlprocess.Items.Insert(0, "")
End If
End Sub
Private Sub FillEquipment(ByVal level2_ID As Integer) '3rd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level3_id, [LCODE3]+ ' | '+[LNAME3] as [LCODE3] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level2_id = #level2_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level2_id", SqlDbType.Int).Value = level2_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
equipment.DataSource = dt
equipment.DataTextField = "LCODE3"
equipment.DataValueField = "level3_id"
equipment.DataBind()
equipment.Items.Insert(0, "")
End If
End Sub
Private Sub FillStep(ByVal level3_ID As Integer) '4th dropdown
Dim dt As New DataTable
Dim strSql = "select distinct [LCODE4]+ ' | '+[LNAME4] as [LCODE4] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level3_id = #level3_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level3_id", SqlDbType.Int).Value = level3_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
[step].DataSource = dt
[step].DataTextField = "LCODE4"
[step].DataBind()
[step].Items.Insert(0, "")
End If
End Sub
The reason I want a blank 1st row is so that when the form loads I want all dropdownlist to start off empty. During testing I thought to try selecting back to blank 1st row after selecting a value. This causes an error to occur at:
'Any one of the selectedindexchanged sub depending on which list I used
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString()) '--> issue here
FillProcess(level1_ID)
End Sub
Error message being:
Input string was not in a correct format.
Anything I can do to fix this?

Why does this "Is" test fail with this comparison?

I have this code to compare the value of two control tag values:
Protected Function GetLabelTextForTag(tagVal As String) As String
Dim CoName As String = ""
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is Label Then
If DirectCast(cntrl, Label).Tag Is tagVal Then
CoName = DirectCast(cntrl, Label).Text
Exit For
End If
End If
Next
Return CoName
End Function
Even when I get to this line, though:
If DirectCast(cntrl, Label).Tag Is tagVal Then
...and Tag is the same as tagVal ("1"), the next line is not reached - "1" is not seen as being the same thing as "1"
Not being familiar with VB, I thought maybe the "Is" was the problem. But the reason I used "IS" to begin with, though, is because when I first tried this:
If DirectCast(cntrl, Label).Tag = tagVal Then
...I got, "Error 1 Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity."
The function is called by an event handler for a button click:
Private Sub Button1_Click( sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curTagVal As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If DirectCast(cntrl, CheckBox).Checked = True Then
curTagVal = CStr(DirectCast(cntrl, CheckBox).Tag)
coName = GetLabelTextForTag(curTagVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
conn.Open
cmd.ExecuteScalar()
End Using
End If
End If
Next
End Sub
I'm looking for labels and checkboxes with the same tag value, because I'm dynamically creating some pairs of these controls, and need to know which corresponding checkboxes are checked for which labels. I create them (a few, this is just a test) like so:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConnection1 As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "select C.CompanyName from CustomerCategoryLog CCL join Customers C on C.CustNo = CCL.Custno where CCL.Category = 'New' and C.Active <> 0 order by C.CompanyName"
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
If reader.HasRows Then
Dim i As Integer = 0
While reader.Read()
i = i+1
If i > 12 'There are thousands...just grab the first dozen for this test
Exit While
End If
Dim lblCompanyName = New Label()
lblCompanyName.Tag = i.ToString() 'ID not available...?!?
lblCompanyName.Text = reader.Item(0).ToString()
Me.Controls.Add(lblCompanyName)
Dim ckbx = New CheckBox()
ckbx.Tag = i.ToString()
ckbx.Checked = True
Me.Controls.Add(ckbx)
End While
End If
reader.Close()
sqlConnection1.Close()
End Sub
I may as well add the only other bit of code on the form, too, for good measure:
Protected Function GetArgValsForCompanyName(coName As String) As String()
Dim args(2) As String
Dim sqlConnection1 As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
If reader.HasRows Then
args(0) = reader.Item(0).ToString()
args(1) = reader.Item(1).ToString()
args(2) = reader.Item(2).ToString()
End If
reader.Close()
sqlConnection1.Close()
Return args
End Function
When is "1" not "1"?
Okay, Tag is an Object not a String hence with option strict on you get the issue, try
If DirectCast(cntrl, Label).Tag.ToString() = tagVal Then
Using Is you are comparing references not values.
Fixed this for you too
Private Sub Button1_Click( sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curTagVal As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If DirectCast(cntrl, CheckBox).Checked = True Then
curTagVal = CStr(DirectCast(cntrl, CheckBox).Tag)
coName = GetLabelTextForTag(curTagVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
conn.Open
cmd.ExecuteScalar()
End Using
End If
End If
Next
End Sub
I still don't know why the original code didn't work, but chaning it to the following does:
Protected Function GetLabelTextForTag(tagVal As String) As String
Dim CoName As String = ""
Dim lblTag As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is Label Then
lblTag = CStr(DirectCast(cntrl, Label).Tag)
If lblTag = tagVal Then
CoName = DirectCast(cntrl, Label).Text
Exit For
End If
End If
Next
Return CoName
End Function

Link Two Comboboxes vb net

Combobox2 values need to be changed when combobox1 changes value
Private Sub ComboBoxPodelba_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPodelba.SelectedIndexChanged
Dim myconnect As New SqlConnection
myconnect.ConnectionString = Common.connectionString
Dim mycommand2 As SqlCommand = New SqlCommand()
mycommand2.Connection = myconnect
Try
myconnect.Open()
mycommand2.CommandText = "select PodPodelbaIme from PodPodelba where PodelbaFK = '" + ComboBoxPodelba.SelectedValue.ToString + "'"
Dim reader2 As SqlDataReader
reader2 = mycommand2.ExecuteReader()
Dim dt2 As DataTable = New DataTable
dt2.Load(reader2)
ComboBoxPOdPodelba.ValueMember = "PodPodelbaIme"
ComboBoxPOdPodelba.DisplayMember = "PodPodelbaIme"
ComboBoxPOdPodelba.DataSource = dt2
Catch ex As Exception
End Try
End Sub
Try...
Private Sub Combo1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combo1.SelectedIndexChanged
Dim myconnect As New SqlConnection
myconnect.ConnectionString = Common.connectionString
Dim mycommand2 As SqlCommand = New SqlCommand()
mycommand2.Connection = myconnect
Try
myconnect.Open()
mycommand2.CommandText = "select PodPodelbaIme from PodPodelba where PodelbaFK = '" + Sender.SelectedValue.ToString + "'"
Dim reader2 As SqlDataReader
reader2 = mycommand2.ExecuteReader()
Dim dt2 As DataTable = New DataTable
dt2.Load(reader2)
Combo2.ValueMember = "PodPodelbaIme"
Combo2.DisplayMember = "PodPodelbaIme"
Combo2.DataSource = dt2
Catch ex As Exception
End Try
End Sub

Populating Textbox and DropdownLists

I am having a hard time trying to populate a textbox, and two dropdown lists. What I am attempting to do is this: when the Company dropdownlist has been selected, it will display a grid of its respective values from a sqldatasource, which it does. Now the next step is once a selection from the company dropdown has been made, a textbox will display the membertype as well as the second dropdownlist. The third dropdown displays the groupid. All these three components have their outputs after a selection has been made. But I cannot seem to get the values to show. I also added code for clarification.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls
Partial Class companydropdown
Inherits System.Web.UI.Page
Private Sub BindDropDownList(DropdownList1 As DropDownList, query As String, text As String, value As String, defaultText As String)
If Not IsPostBack Then
' Read sql server connection string from web.config file
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
'da.Fill(dt)
End Using
'DropdownList1.DataSource = dt
DropdownList1.DataTextField = "CompanyName"
DropdownList1.DataValueField = "CompanyID"
DropdownList1.DataBind()
'DropdownList1.Items.Insert(0, New ListItem("--Select--"))
End If
End Sub
Protected Sub Member_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList2.DataTextField = "MembershipStatus"
DropDownList2.DataValueField = "MemberTypeID"
' Bind sql server data into the Dropdown List
DropDownList2.DataBind()
Else
DropDownList2.Items.Clear()
End If
End Sub
Protected Sub Group_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList3.DataTextField = "GroupID"
DropDownList3.DataValueField = "GroupID"
' Bind sql server data into the Dropdown List
DropDownList3.DataBind()
Else
DropDownList3.Items.Clear()
End If
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
DropDownList2.Enabled = False
'DropDownList3.Items.Clear()
DropDownList3.Items.Insert(0, New ListItem("", "0"))
Dim stateId As Integer = Integer.Parse(DropDownList1.SelectedItem.Value)
If stateId > 0 Then
Dim query As String = String.Format("", stateId)
BindDropDownList(DropDownList1, query, "CompanyName", "CompanyId", "")
DropDownList3.Enabled = True
DropDownList2.Enabled = True
End If
End Sub
End Class

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class