vb.net - 如何使用多个文本框和一个搜索按钮进行搜索
问题描述
我正在使用 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 的新手,非常感谢一些帮助。
解决方案
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
此代码将搜索填写的文本框中提供的条件。它不假定未填写的文本框在数据库中的关联字段中必须有空数据。
推荐阅读
- html - 为 imacro 编写宏脚本
- java - 在 .classpath 文件 eclipse 中设置 jar 文件的相对路径
- c++ - Box2D OpenGL 错误
- vue.js - 如何在模块中使用 nuxt 挂钩?
- npm - 安装一个“匹配”项目依赖项的依赖项
- javascript - 与 Office UI Fabric 反应 - InputChildren 未触发 onSubmit/onClick
- c++ - 在 C++ 中创建类型向量
- c# - 没有从 api 控制器引用业务逻辑?
- ecmascript-6 - 从 ES2018 async/await 到 ES2015 Promises 。... 超时
- cmake - CTest:如果“预检查”测试失败,如何跳过其他测试?