how can i fix this error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" - vb.net

I have a gridview when i click the column of the dataGridview the problem show
"error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index""
how can i fix this? please help
this is the whole code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'construct dataGridview
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "name"
DataGridView1.Columns(1).Name = "position"
DataGridView1.Columns(2).Name = "team"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
End Sub
Private Sub Populate(name As String, pos As String, team As String)
Dim row As String() = New String() {name, pos, team}
DataGridView1.Rows.Add(row)
End Sub
Private Sub Retrieve()
DataGridView1.Rows.Clear()
Dim sql As String = "SELECT * FROM peopleTB"
cmd = New OleDbCommand(sql, con)
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.fill(dt)
'fill dgview
For Each row In dt.Rows
Populate(row(1), row(2), row(3))
Next
con.Close()
dt.Rows.Clear()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Cleartxt()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
'update db and dg
Private Sub UpdateDG(name As String)
Dim sql As String = "UPDATE peopleTB Set N ='" + TextBox1.Text + "',P='" + TextBox2.Text + "',T='" + TextBox3.Text + "'WHERE N= '" + name + "'"
'OPEN CON
Try
con.Open()
adapter.updateCommand = con.CreateCommand()
adapter.updateCommand.commandtext = sql
If adapter.updateCommand.executenonquery() > 0 Then
MsgBox("Success updated")
Cleartxt()
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(2).Value
TextBox1.Text = name
TextBox2.Text = position
TextBox3.Text = team
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(name)
End Sub
Im using ms access

Related

Read a SQL table cell value and only change a ComboBox.text without changing the ComboBox collection items

I'm trying to make an army list builder for a miniatures strategy game.
I'd like to know the correct method to read a SQL table cell value and to put it for each unit into a ComboBox.text field, but only into the field.
The ComBoBox collection items should not be modified (I need them to remain as it is). I just want the ComboBox.text value to be modified with the red framed value, and for each unit
For the record, currently, I read the others table informations and load them into the others ComboBoxes this way :
Private Sub TextBoxQuantitéUnités_Click(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select * from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "nom_unité"
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutTotal.DataSource = dt
ComboBoxCoutTotal.DisplayMember = "cout_unité"
connection.Close()
End Sub
Many thanks :-)
The ComboBox.text where I want to load the cell value
The table picture with the framed value I want to load into the cell
The original ComboBox collection I want to keep
EDIT 2 :
My table structure
Your function call
A short clip of the program in order to understand my problem
As you can see, the function seems good and when I check the ComboBoxQuality text during the execution, it seems good but for some reason, it don't change...
The others Comboboxes are sync as you can see on the upper code.
Thanks in advance...
EDIT 3:
The whole code as requested :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class FormOst
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN = New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Private Sub TextBoListeArmées_Click(sender As Object, e As EventArgs) Handles TextBoxListeArmées.Click
Dim connection As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select [nom_unité] + ' | ' + [abréviation_unité] as Unité, index_unité, abréviation_unité, type_unité, qualité_unité, cout_unité from liste1 Order By index_unité"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
ComboBoxNomUnités.DataSource = dt
ComboBoxNomUnités.DisplayMember = "Unité"
ComboBoxNomUnités.AutoCompleteMode = AutoCompleteMode.Append
ComboBoxNomUnités.AutoCompleteSource = AutoCompleteSource.ListItems
ComboBoxTypeUnités.DataSource = dt
ComboBoxTypeUnités.DisplayMember = "type_unité"
ComboBoxAbréviationUnités.DataSource = dt
ComboBoxAbréviationUnités.DisplayMember = "abréviation_unité"
ComboBoxCoutUnité.DataSource = dt
ComboBoxCoutUnité.DisplayMember = "cout_unité"
LabelListeChargéeVisible.Enabled = True
LabelListeChargée.Visible = True
connection.Close()
End Sub
Private Sub TextBoxQuantitéUnités_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBoxQuantitéUnités.KeyPress
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
Private Sub TextBoxQuantitéUnités_TextChanged(sender As Object, e As EventArgs) Handles TextBoxQuantitéUnités.TextChanged
Try
TextBoxCoutTotal.Text = (Decimal.Parse(TextBoxQuantitéUnités.Text) * Decimal.Parse(ComboBoxCoutUnité.Text)).ToString()
Catch ex As Exception
End Try
End Sub
Private Sub ButtonEffacer_Click(sender As Object, e As EventArgs) Handles ButtonEffacer.Click
TextBoxQuantitéUnités.Text = ""
ComboBoxNomUnités.Text = ""
ComboBoxTypeUnités.Text = ""
ComboBoxQualitéUnités.Text = ""
ComboBoxAbréviationUnités.Text = ""
ComboBoxCoutUnité.Text = ""
TextBoxCoutTotal.Text = ""
End Sub
Private Sub LabelListeChargéeVisible_Tick(sender As Object, e As EventArgs) Handles LabelListeChargéeVisible.Tick
LabelListeChargée.Visible = False
LabelListeChargéeVisible.Enabled = False
End Sub
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
'' TextBoxCoutTotal.Text = (Decimal.Parse(ComboBoxCoutUnité.SelectedItem.ToString) * Decimal.Parse(TextBoxQuantitéUnités.Text)).ToString
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 ORDER BY index_unité")
Catch ex As Exception
End Try
End Sub
End Class
Function for retrieving your data via sql query
Public Function GetStringFromQuery(ByVal SQLQuery As String) As String
Dim CN As New SqlConnection("Data Source=Server;Initial Catalog=OST;Integrated Security=True")
CN.Open()
Dim StrSql As String = SQLQuery
Dim cmdReader As SqlCommand = New SqlCommand(StrSql, CN)
cmdReader.CommandType = CommandType.Text
Dim SdrReader As SqlDataReader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection)
'SdrReader = cmdReader.ExecuteReader
GetStringFromQuery = ""
Try
With SdrReader
If .HasRows Then
While .Read
If .GetValue(0) Is DBNull.Value Then
GetStringFromQuery = ""
Else
If IsDBNull(.GetValue(0).ToString) Then
GetStringFromQuery = ""
Else
GetStringFromQuery = .GetValue(0).ToString
End If
End If
End While
End If
End With
CN.Close()
Catch ex As Exception
MsgBox(SQLQuery, MsgBoxStyle.Exclamation, "Error")
End Try
End Function
Retrieve data and put into your combo box text
ComboBox.Text = GetStringFromQuery("Enter Sql Query here")
Your sql query problem.
Your query select everything and you suppose to return the UOM that relate to your item
Private Sub ComboBoxNomUnités_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBoxNomUnités.SelectionChangeCommitted
Try
Dim Product as string = ComboBoxNomUnités.Text
ComboBoxQualitéUnités.Text = GetStringFromQuery("SELECT qualité_unité FROM liste1 Where Nom_Unité = '" & Product & "'")
Catch ex As Exception
End Try
End Sub

object reference not set to an instance of an object Inserting database sql array

How can i insert array textbox in database?I have to save each newboxes in access and it should be in different row..It has an error object reference not set to an instance of an object when saving the data
Public Class Form1
Dim boxes As New List(Of TextBox)
Dim combo As New List(Of ComboBox)
Private Sub Addbuttons(buttonCount As Integer)
Dim newbox As TextBox Dim newcombo As ComboBox
For i As Integer = 1 To buttonCount
newbox = New TextBox
newbox.Size = New Drawing.Size(575, 35)
newbox.Location = New Drawing.Point(10, 10 + 35 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name
'connect it to a handler, save a reference to the array and add it to the form controls
boxes.Add(newbox)
Me.Controls.Add(newbox)
Next For i As Integer = 1 To buttonCount
newcombo = New ComboBox
newcombo.Size = New Drawing.Size(57, 20)
newcombo.Location = New Drawing.Point(864, 531 + 70 * (i - 1))
combo.Add(newcombo)
Me.Controls.Add(newcombo)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Addbuttons(Val(TextBox1.Text))
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
addbuyer()
End Sub
Private Sub addbuyer()
Dim newbox As TextBox
Try
datab = " Insert INTO sample (sample1,sample2) values ( '" & newbox.Text & "','" & newqty.Text & "')"
connDB()
cmd = New OleDbCommand(datab, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
' MsgBox("Added SUccesfully", MsgBoxStyle.Information, "Confirmation")
Else
MsgBox("Failed Adding", MsgBoxStyle.Information, "Alert!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
End Class
In addbuyer, Dim newbox As TextBox is nothing and that's the cause of the error.
You added all the textbox controls to boxes so you need to loop thru that when you insert into the DB. One way to do it is by looping and passing each textbox by reference:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
For Each t As TextBox In boxes
addbuyer(t)
Next
End Sub
Private Sub addbuyer(ByRef newbox As TextBox)
Try
datab = " Insert INTO sample (sample1) values ( '" & newbox.Text & "')"
connDB()
cmd = New OleDbCommand(datab, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Added SUccesfully", MsgBoxStyle.Information, "Confirmation")
Else
MsgBox("Failed Adding", MsgBoxStyle.Information, "Alert!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub

How to insert, edit, delete image in SQL using vb.net

I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.
Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)
Sub NormalUpdate(ByVal _Query)
con.Open()
Dim cmdUpdate As New SqlCommand(_Query)
cmdUpdate.Connection = con
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.ExecuteNonQuery()
con.Close()
End Sub
Sub NormalSave(ByVal _Query)
con.Open()
Dim cmdSave As New SqlCommand(_Query)
cmdSave.Connection = con
cmdSave.CommandType = CommandType.Text
cmdSave.ExecuteNonQuery()
con.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
Using dt As New DataTable
dt.Load(dr)
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
Dim img As Image = Image.FromStream(ms)
ProfilePic.Image = img
con.Close()
End Using
End Using
End Using
End Using
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub
Please help me. Thanks.
Not sure if this is what you are looking for, but I use the following to get and set images from a database:
Public Function GetClientImage(ID As String) As Image
Dim ClientPicture As Image = Nothing
Dim DS As DataSet = Nothing
'Populate DS here
If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then
Dim DR As DataRow = DS.Tables(0).Rows(0)
Try
Dim Pic As Object = DR!Picture
If Pic IsNot DBNull.Value Then
Dim Buffer As Byte() = CType(DR!Picture, Byte())
If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
MS.Write(Buffer, 0, Buffer.Length)
ClientPicture = Image.FromStream(MS, True)
End Using
End If
End If
Catch ex As Exception
MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End If
Return ClientPicture
End Function
and:
Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
Dim Result As Integer = 0
If Client IsNot Nothing Then
Dim SQL As String = "UPDATE Clients SET Picture = #photo WHERE ID = '" & ID & "' ;"
Using SQLConn As New SqlClient.SqlConnection(ConnectionString)
Try
SQLConn.Open()
Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)
Dim PhotoParameter As New SqlClient.SqlParameter("#photo", SqlDbType.Image)
Dim MS As New IO.MemoryStream()
If Pic IsNot Nothing Then
Pic.Save(MS, Imaging.ImageFormat.Bmp)
End If
PhotoParameter.SqlValue = MS.GetBuffer
SQLCmd.Parameters.Add(PhotoParameter)
Result = SQLCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Dim Msg As String = "Unable to save Client's Picture"
If ex IsNot Nothing Then
Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
End If
MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
If Not SQLConn.State = ConnectionState.Closed Then
SQLConn.Close()
End If
End Try
End Using
End If
Return Result
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles
Dim OpennFileDialog As OpenFileDialog
query = "update tblEmployeeSetup set dbImage = #dbImage where empy_id = '" + txtEmpId.Text + "' "
insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub
Sub insertImage(ByVal query As String, ByVal message As String, ByVal lblSave As Label, ByVal a As OpenFileDialog)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim result As DialogResult = a.ShowDialog()
' a.FileName = My.Resources.DefultImage.ToString
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.Add(New SqlClient.SqlParameter("#dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
lblSave.Text = message
a.Dispose()
Catch ex As Exception
MessageBox.Show("Error" & ex.Message)
Finally
con.Close()
End Try
End Sub

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

how to display the data with combo box

Sub CboSO_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles CboSO.DropDown
If functionmode = "UPDATE" Then
Dim daProp2 As New OdbcDataAdapter()
Dim dsProp2 As New DataSet()
Dim qryProp2 As String
qryProp2 = "SELECT num FROM so WHERE scn = '" & txtSCN.Text & " '"
daProp2.SelectCommand = New OdbcCommand(qryProp2, conn)
Dim cb2 As OdbcCommandBuilder = New OdbcCommandBuilder(daProp2)
daProp2.Fill(dsProp2, "so")
Dim dtRbt As DataTable = dsProp2.Tables("so")
Try
If dsProp2.Tables(0).Rows.Count > 0 Then
CboSO.DropDownStyle = ComboBoxStyle.DropDownList
CboSO.DataSource = dsProp2
CboSO.DisplayMember = "num"
End If
Catch ex As OdbcException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
End If
End Sub
Assign the DataTable object reference.
CboSO.DataSource = dtRbt
CboSO.DisplayMember = "num"