我正在尝试使用文本框从数据库中选择数据并将其显示在gridview的新行上。将使用条形码扫描仪输入文本框。我只需要扫描条形码然后搜索数据库中的数据并将其添加到gridview的新行。它将使用ontextchange事件执行。
到目前为止,这是我的代码:
Private Sub selectData(ByVal rowcount As Integer)
sql = "Select Barcode, Name from tbl_barcode where [Barcode] = '" + txtScanBarcode.Text + "'"
cmd = New SqlCommand(sql, con)
drDataReader = cmd.ExecuteReader
While (drDataReader.Read())
dtDatatable.Columns.Add(New System.Data.DataColumn("Barcode", GetType([String]))) '0
dtDatatable.Columns.Add(New System.Data.DataColumn("Name", GetType([String]))) '1
If Session("CurrentData") IsNot Nothing Then
For i As Integer = 0 To rowcount
dtDatatable = DirectCast(Session("CurrentData"), DataTable)
If dtDatatable.Rows.Count > 0 Then
dr = dtDatatable.NewRow()
dr(0) = "Barcode"
dr(1) = "Name"
End If
Next
dr = dtDatatable.NewRow()
dr(0) = "Barcode"
dr(1) = "Name"
dtDatatable.Rows.Add(dr)
Else
dr = dtDatatable.NewRow()
dr(0) = "Barcode"
dr(1) = "Name"
dtDatatable.Rows.Add(dr)
End If
End While
If Session("CurrentData") IsNot Nothing Then
dtDatatable.Load(drDataReader)
GridView1.DataSource = DirectCast(Session("CurrentData"), DataTable)
GridView1.DataBind()
Else
dtDatatable.Load(drDataReader)
GridView1.DataSource = dtDatatable
GridView1.DataBind()
End If
Session("CurrentData") = dtDatatable
End Sub
Protected Sub txtScanBarcode_TextChanged(sender As Object, e As EventArgs) Handles txtScanBarcode.TextChanged
If Session("CurrentData") IsNot Nothing Then
Dim dt As DataTable = DirectCast(Session("CurrentData"), DataTable)
Dim count As Integer = dt.Rows.Count
selectData(count)
Else
selectData(1)
End If
End Sub
以上代码,能够添加新行但无法从数据库中获取数据。当我执行它并扫描条形码时,它不显示数据库中的数据,它在dr(0)上添加文本'Barcode',在dr(1)上添加文本'name'。所以,我认为用于从数据库获取数据的sql不起作用。它不会调用数据库中的任何数据。 你有什么建议吗,如何从数据库中选择数据并将其提取到行中?
提前致谢。我真的很感激。
答案 0 :(得分:1)
尽量不要使用阅读器,而是使用DataSet然后获取数据
Public Function getDataInDB(ByVal sQuery As String) As String
getDataInDB = Nothing
Try
CMD = New SqlCommand(sQuery, TestResult)
Dim sqlAdapter As SqlDataAdapter
Dim dataS As DataSet
sqlAdapter = New SqlDataAdapter(CMD)
dataS = New DataSet
sqlAdapter.Fill(dataS, "getRecord")
getDataInDB = dataS.Tables("getRecord").Rows(0).ItemArray(0).ToString()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
通过不使用阅读器,获得这样的数据会更安全,更快......