【问题标题】:Passing barcode scan from textbox into a multiline textbox将条形码扫描从文本框传递到多行文本框
【发布时间】:2015-05-26 11:42:08
【问题描述】:

好的,坚持了一会儿,需要建议 - 我有将条形码扫描到文本字段并使用该文本字段查询数据库的表单,它从产品表中返回 PRICE。但是当我扫描下一个项目时,我得到了下面描述的错误。就像它同时寻找两个条形码一样...但是在将 PRICE 添加到项目文本框后,我将保存条形码的文本字段设置为清除

我的代码:

    Private Sub txtTest_KeyDown(ByVal sender As Object, _

ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox3.KeyDown

        If e.KeyCode = Keys.Enter Then



            Dim con As New OleDbConnection

            Dim databaseprovider As String

            Dim dblocation As String





            databaseprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"

            dblocation = "Data Source = C:\Users\fergus\desktop\Loft Hair Studio Till App\loft.accdb"

            con.ConnectionString = databaseprovider & dblocation



            Dim queryLoft As String = "SELECT Price from Services where Field1 =" & TextBox3.Text & ""



            Dim command As New OleDbCommand(queryLoft, con)



            con.Open()



            Dim myreader As OleDbDataReader = command.ExecuteReader()



            myreader.Read() 'Read the next line from the DataReader



            'ListBox1.Text = myreader("price").ToString

            TextBoxList.Text = myreader("price").ToString

            'TextBox1.Text = myreader("price").ToString



            TextBoxTest.Clear()


        End If

    End Sub

错误:

oledbexception 未处理

查询表达式'Field1 = 61542451 61524587'中的语法错误(缺少运算符)

就像它同时在数据库中搜索 2 个条形码号码一样。

看起来很奇怪。

任何帮助表示赞赏

【问题讨论】:

  • 您没有从文本框中清除文本,您正在痛苦地、危险地在查询字符串中内联而不是参数化。
  • 嗨,赫尔里希,我是新手。你能给我解释一下吗?你的意思是我需要对 textbox3 使用 clear 方法吗?
  • 哪个文本框包含扫描的条形码?看起来 TextBox3 是您要连接到查询的那个,所以它似乎是要清除的那个。我会第二次@helrich 评论关于使用参数而不是像这样的连接。

标签: vb.net textbox barcode


【解决方案1】:

我注意到您的事件处理程序被命名为 txtTest_KeyDown 但它正在处理 TextBox3。我猜你会想在处理完扫描后清除 TextBox3。

Private Sub TextBox3_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox3.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.Handled = True

        Using cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\users\fergus\desktop\Loft Hair Studio Till App\loft.accdb")
            cn.Open()

            Using cmd = New OleDbCommand("SELECT Price FROM Services WHERE Field1=?", cn)
                cmd.Parameters.AddWithValue("@scan", TextBox3.Text)

                Using reader = cmd.ExecuteReader()
                    If reader.Read Then
                        TextBoxList.Text = reader("price").ToString
                        TextBox3.Clear()
                    End If
                End Using
            End Using
        End Using
    End If
End Sub

此外,对一次性资源(例如连接、命令和读取器)使用 Using 语句是一种很好的做法。

【讨论】: