Searching In datagridview in Windows Application VB.NET - vb.net

I have to filter datagridview using textbox.The code below I am using to fill gridview.getdata function of db class returns the datatable.
I am not using datasource property of gridview instead I am filing gridview using loop.
I can do searching using datasource property and dataview but i have not to fill datagridview directly from datasource property.
Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
If DTT.Rows.Count > 0 Then
For i As Integer = 0 To DTT.Rows.Count - 1
DataGridView1.Rows.Add()
DataGridView1.Rows(i).Cells("crime").Value = DTT.Rows(i).Item("crime") & ""
DataGridView1.Rows(i).Cells("actname").Value = DTT.Rows(i).Item("actname") & ""
DataGridView1.Rows(i).Cells("section").Value = DTT.Rows(i).Item("section") & ""
DataGridView1.Rows(i).Cells("description").Value = DTT.Rows(i).Item("description") & ""
Next
End If
End Sub

Use the WHERE statement in your SQL Query
"SELECT crime,actname,section,description from natureofcomplaint_women WHERE crime = " & txtSearch.text
(If you want to search on crime.)
Change to your needs.
Just repeat the datagrid fill you used above, but with an altereted SQL query each time you type/press the search button

I still think it's best to bind...
Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
Dim source1 as New BindingSource()
source1.DataSource = DTT
source1.Filter = "crime = '" & textboxtCrime.text & "'"
DataGrideView1.DataSource = source1
End Sub

Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
If DTT.Rows.Count > 0 Then
For i As Integer = 0 To DTT.Rows.Count - 1
If (DTT.Rows(i).Item("Crime").Contains(txtCrimeFilter.Text) AND & _
(DTT.Rows(i).Item("actname").Contains(txtActnameFilter.Text) AND & _
(DTT.Rows(i).Item("section").Contains(txtSectionFilter.Text) AND & _
(DTT.Rows(i).Item("description").Contains(txtDescriptionFilter.Text)
DataGridView1.Rows.Add()
DataGridView1.Rows(i).Cells("crime").Value = DTT.Rows(i).Item("crime") & ""
DataGridView1.Rows(i).Cells("actname").Value = DTT.Rows(i).Item("actname") & ""
DataGridView1.Rows(i).Cells("section").Value = DTT.Rows(i).Item("section") & ""
DataGridView1.Rows(i).Cells("description").Value = DTT.Rows(i).Item("description") & ""
End If
Next
End If
End Sub

Related

Runtime datatable update error

I have a datagridview with a checkbox column. When I click(check/Uncheck) on checkbox field as random, two other fields in corrensponding row should be added OR removed in a datatable (declared runtime).
So that I can do some procedures with data in the datatable.
For that I have declared a datatable as global.
Now the problem is, each time when I click on a checkbox, a simple mouse scrolling is required to update datatable, OR a click needed in the new datagridview which is showing values in the datatable.
My code given below,
global declaration: Public PaymentTable As DataTable
Private Sub ShowOrdersFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataBind()
Me.DGVOrders.RowsDefaultCellStyle.BackColor = Color.GhostWhite
Me.DGVOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleGoldenrod
PaymentTable = New DataTable()
PaymentTable.Columns.Add("RowId", GetType(Integer))
PaymentTable.Columns.Add("Amount", GetType(Decimal))
End Sub
Private Sub DataBind()
DGVOrders.DataSource = Nothing
DGVOrders.Columns.Clear()
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "select * from VIEW_PAYMENTS_DUES_BYORDER where CustCode='" & CustCode & "' order by OrderNo DESC"
End With
da.SelectCommand = cmd
da.Fill(dt)
BindingSource1.DataSource = dt
DGVOrders.DataSource = BindingSource1
DGVOrders.ClearSelection()
con.Close()
DGVOrders.Columns(0).Visible = False
DGVOrders.Columns(1).HeaderText = "Order No"
DGVOrders.Columns(2).HeaderText = "Cust Code"
DGVOrders.Columns(3).HeaderText = "Name"
DGVOrders.Columns(4).HeaderText = "Order Date"
DGVOrders.Columns(5).HeaderText = "Order Price"
DGVOrders.Columns(6).HeaderText = "Total Payment"
DGVOrders.Columns(7).HeaderText = "Dues"
For i = 0 To DGVOrders.RowCount - 1
If DGVOrders.Rows(i).Cells(7).Value > 0 Then
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Red
Else
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Green
End If
Next
' CHECK BOX
Dim colmnchk As New DataGridViewCheckBoxColumn
colmnchk.DataPropertyName = "chkSelect"
colmnchk.HeaderText = "SELECT"
colmnchk.Name = "chkSelect"
DGVOrders.Columns.Add(colmnchk)
For i = 0 To DGVOrders.RowCount - 1
Next
'CHECK BOX END
End Sub
Private Sub DGVOrders_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOrders.CellValueChanged
If DGVOrders.Columns(e.ColumnIndex).Name = "chkSelect" Then
Dim checkCell As DataGridViewCheckBoxCell = _
CType(DGVOrders.Rows(e.RowIndex).Cells("chkSelect"), _
DataGridViewCheckBoxCell)
If checkCell.Value = True Then
PaymentTable.Rows.Add(DGVOrders.Rows(e.RowIndex).Cells(0).Value, DGVOrders.Rows(e.RowIndex).Cells(7).Value)
Else
Dim toRemoveID As Integer = DGVOrders.Rows(e.RowIndex).Cells(0).Value
For i = 0 To PaymentTable.Rows.Count - 1
If PaymentTable.Rows(i).Item(0) = toRemoveID Then
PaymentTable.Rows(i).Delete()
Exit Sub
End If
Next
End If
DataGridView1.DataSource = PaymentTable
End If
End Sub
Can sombody to solve the issue, or is there any other good method if my code is wrong ?
Try using a different event like CellContentClick and testing for the ColumnIndex. The drawback with this is the event will fire whenever you click on any cell.
Private Sub DGVOrders_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVOrders.CellContentClick
'Only interested in the CheckBox column
If e.ColumnIndex = colmnchk.Index Then
Debug.WriteLine("In DGVOrders_CellContentClick for the checkbox")
End If
End Sub

Updating data in gridview using vb.net

First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database

Datatable:xml query for xml column

If i load xml datatype column to a datatable then can i perform xml query on it? SQL server supports queries like .exist, .value on xml columns. I am trying those kind of queries on datatable.
Below is a part of code which shows where i am getting error.
Private Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Click
Dim timDiff As Double
Dim iter1 As Integer
TextBox1.Text &= Button15.Text & vbNewLine & " Iterations: " & TextBox2.Text & vbNewLine
timDiff = DateAndTime.Timer
Dim SqlAdapter As New SqlDataAdapter
Dim strTemp As String
Dim iRow As Integer
Dim rConn As New SqlConnection("data source=pc91\sqlexpress;user id=admin;password=abc;initial catalog=Checklists;connect timeout=2000;")
rConn.Open()
SqlAdapter = New SqlDataAdapter
sDataSet = New DataSet
sqldatatable = Nothing
SqlAdapter.SelectCommand = New SqlCommand("select * from DesignChanges", rConn)
SqlAdapter.Fill(sDataSet, "tmpTable")
sqldatatable = sDataSet.Tables("tmpTable")
For iter1 = 1 To Val(TextBox2.Text)
Try
For iRow = 0 To sqldatatable.Rows.Count - 1
strTemp = sqldatatable.Rows(iRow).Item("AllotedTo").ToString
Next iRow
Catch ex As Exception
MsgBox(ex.ToString & Space(10) & Err.Description)
End Try
Next
rConn.Close()
SqlAdapter.Dispose()
rConn.Dispose()
sDataSet = Nothing
SqlAdapter = Nothing
rConn = Nothing
timDiff = DateAndTime.Timer - timDiff
TextBox1.Text &= " Total Time Taken: " & timDiff & vbNewLine
End Sub
Private Sub Button17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button17.Click
bs.DataSource = sqldatatable
DataGridView1.DataSource = bs
End Sub
Private Sub Button18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button18.Click
bs.Filter = "[UserApproval].exist ('/Root/Row[User=''xyz'']') =1"
End Sub
End Class
In the above code error comes like "The expression contains undefined function call UserApproval.exist()." for the line bs.Filter = "[UserApproval].exist ('/Root/Row[User=''xyz'']') =1" .
If i use .value function then error will come as "The expression contains undefined function call UserApproval.value()."
But the same functions works in SQL query for sql server.
Yes, you can. Did you read this? What kind of queries do not work well?

looping through all records on the database

i revised the code a little from a friend
but it only display the first record how will i able to manipulate to loop through all records
anyone who could give correct answer in code will receive bounty thanks
Note: DisplayOfficeEquipmentList() is a sub that displays data on the database to the textboxes and comboboxes
Public Sub DisplayOfficeEquipmentList()
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim dt As New DataTable
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentProfile", sqlconn)
da.Fill(dt)
cmbCategory.Text = dt.Rows(0)("OE_Category").ToString()
cmbSubCategory.Text = dt.Rows(0)("OE_SubCategory").ToString()
txtOEID.Text = dt.Rows(0)("OE_ID").ToString()
txtName.Text = dt.Rows(0)("OE_Name").ToString()
txtUser.Text = dt.Rows(0)("OE_User").ToString()
cmbBrand.Text = dt.Rows(0)("OE_Brand").ToString()
cmbModel.Text = dt.Rows(0)("OE_Model").ToString()
txtSpecs.Text = dt.Rows(0)("OE_Specs").ToString()
txtSerialNo.Text = dt.Rows(0)("OE_SerialNo").ToString()
txtPropertyNo.Text = dt.Rows(0)("OE_PropertyNo").ToString()
txtMacAddress.Text = dt.Rows(0)("OE_MacAddress").ToString()
txtStaticIP.Text = dt.Rows(0)("OE_Static_IP").ToString()
txtVendor.Text = dt.Rows(0)("OE_Vendor").ToString()
dtpPurchaseDate.Text = dt.Rows(0)("OE_PurchaseDate").ToString()
txtWarrantyStatus.Text = dt.Rows(0)("OE_WarrantyStatus").ToString()
txtWarrantyInclusiveYear.Text = dt.Rows(0)("OE_WarrantyInclusiveYear").ToString()
txtStatus.Text = dt.Rows(0)("OE_Status").ToString()
cmbDeptCode.Text = dt.Rows(0)("OE_Dept_Code").ToString()
cmbLocationCode.Text = dt.Rows(0)("OE_Location_Code").ToString()
txtRemarks.Text = dt.Rows(0)("OE_Remarks").ToString()
sqlconn.Close()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
End Sub
You have to loop the lines, you are getting the values of the row at index 0( Just one row).
Use foreach:
foreach (System.Data.DataRow row in dt.Rows)
{
//Get values of row
}
EDIT: In vb.net it would be something like this:
For Each filarow As DataRow In dt.Rows
Dim OE_ID As String = filarow("OE_ID").ToString
Dim txtName As String = filarow("OE_NAME").ToString
Next
By the way, it seems you are filling textboxes, so the values will change at the next loop. Maybe you should use another control like a ListBox
You need to separate the logic that retrieve data from the logic that shows that data.
First add a method that load your datatable
Private Function LoadData() as DataTable
Using sqlconn = New SqlClient.SqlConnection("server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true")
Dim dt As New DataTable
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentProfile", sqlconn)
da.Fill(dt)
return dt
End Using
End Function
Then in the buttons click pass the datatable and the rownumber to display to the DisplayOfficeEquipmentList
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
if currentRow + 1 >= dt.Rows.Count Then
Return
End if
currentRow = currentRow + 1
DisplayOfficeEquipmentList(dt, currentRow)
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
if currentRow - 1 < 0 Then
Return
End if
currentRow = currentRow - 1
DisplayOfficeEquipmentList(dt, currentRow)
End Sub
and in the DisplayOfficeEquipmentList refer to the row passed by the buttons click
Public Sub DisplayOfficeEquipmentList(ByRef dt as DataTable, ByVal rowNum as INteger)
Dim row as DataRow
row = dt.Rows(rowNum)
cmbCategory.Text = row("OE_Category").ToString()
cmbSubCategory.Text = row("OE_SubCategory").ToString()
....
End Sub
For this to work, you need to call the LoadData somewhere when you show your form (Load event?) and you should set the currentRow as a form global level variable

how to display others data after select data from the 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 * FROM so WHERE scn = '" & txtSCN.Text & " 'AND shutout_ind <> 'N' and so.reload_ind='N' and so.redelv_ind='N'"
daProp2.SelectCommand = New OdbcCommand(qryProp2, conn)
Dim cb2 As OdbcCommandBuilder = New OdbcCommandBuilder(daProp2)
daProp2.Fill(dsProp2, "so")
Dim dtRbt As DataTable = dsProp2.Tables("so")
If dsProp2.Tables(0).Rows.Count > 0 Then
CboSO.DataSource = dtRbt
CboSO.DisplayMember = "so_num"
End If
End If
End Sub
Private Sub CboSO_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles CboSO.KeyPress
Dim daProp3 As New OdbcDataAdapter()
Dim dsProp3 As New DataSet()
Dim qryProp3 As String
qryProp3 = "SELECT SUM(item_num) as totitemnum FROM soitem WHERE scn= '" & txtSCN.Text & " 'AND so_num='" & CboSO.SelectedItem & "' "
daProp3.SelectCommand = New OdbcCommand(qryProp3, conn)
Dim cb3 As OdbcCommandBuilder = New OdbcCommandBuilder(daProp3)
daProp3.Fill(dsProp3, "soitem")
Dim dtRbt As DataTable = dsProp3.Tables("soitem")
If dsProp3.Tables(0).Rows.Count > 0 Then
LblSOQty.Text = IIf(IsDBNull(dsProp3.Tables(0).Rows(0)("totitemnum")), "", dsProp3.Tables(0).Rows(0)("totitemnum"))
End If
End Sub
You have to use CboSO.SelectedValue or CboSO.Text property instead of Cbo.SelectedItem.
PS: Use Parameter (prepare) instead of hard-coded sql string.