首页 > 解决方案 > 如何使用多个文本框和一个搜索按钮进行搜索

问题描述

我正在使用 Visualstudio Visual Basic 进行 Access 数据库连接,我有一个包含 FieldA、FieldB、FieldC 的表(最多 50 个字段)。我不知道如何在表格中搜索包含所需字段的行。对多个字段使用文本框,并使用一个搜索按钮。

例如,在表格中搜索序列号为 1 类型电子产品、名称为 TV 的产品。

我可以使用以下代码查找一个字段:

Dim DA As New OleDbDataAdapter("SELECT * FROM Table1 WHERE Field1 LIKE '" & TBField1.Text & "%'", conexion)
Dim DS As New DataSet
DA.Fill(DS, "Table1")
DGV1.DataSource = DSC.Tables("TPruebaB")

尝试使用它来搜索 2 个字段:

Dim DA As New OleDbDataAdapter("SELECT * FROM Table1 WHERE Field1 LIKE '" & TBField1.Text & "%'", conexion)
Dim DS As New DataSet
Dim DA2 As New OleDbDataAdapter("SELECT * FROM Table1 WHERE Field2 LIKE '" & TBField2.Text & "%'", conexion)
Dim DS2 As New DataSet

DA.Fill(DS, "Table1")
DA2.Fill(DS2, "Table1")
DGV1.DataSource = DS.Tables("Table1")

如果我有

a----b  
a----c  
b----a   
b----c   

这在您搜索“a”作为字段 1 和“b”作为字段 2 时有效,但是当您搜索“b”作为字段 1 和“a”作为字段 2 时这不起作用。

我是使用数据库和 Visual Basic 的新手,非常感谢一些帮助。

标签: vb.netsearch

解决方案


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt As New DataTable
    Dim AndNeeded As Boolean = False
    Dim QueryString = "Select * FROM Table1 WHERE "
    Using cn As New OleDbConnection("Your connection string")
        Using cmd As New OleDbCommand()
            If TextBox1.Text <> "" Then
                If AndNeeded Then
                    QueryString &= "And "
                End If
                QueryString &= "Field1 Like @Field1 "
                cmd.Parameters.Add("@Field1", OleDbType.VarChar).Value = TextBox1.Text & "%"
                AndNeeded = True
            End If
            If TextBox2.Text <> "" Then
                If AndNeeded Then
                    QueryString &= "And "
                End If
                QueryString &= "Field2 Like @Field2 "
                cmd.Parameters.Add("@Field2", OleDbType.VarChar).Value = TextBox2.Text & "%"
                AndNeeded = True
            End If
            'And so on for your 50 text boxes
            QueryString = QueryString.Trim & ";"
            Debug.Print(QueryString) 'just to see what the query looks like
            cmd.CommandText = QueryString
            cmd.Connection = cn
            cn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
    End Using
    DataGridView1.DataSource = dt
End Sub

此代码将搜索填写的文本框中提供的条件。它不假定未填写的文本框在数据库中的关联字段中必须有空数据。


推荐阅读