我想知道是否有一种简单的方法可以使用文本框来搜索数据网格。我已经阅读了一些内容,但我发现的所有示例都来自VS的旧版本。似乎旧版本的VS使用大量代码连接到数据源,因此它使用大量代码进行搜索。我想我可以简化这个吗?
Private Sub Baseball_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players)
End Sub
用数据加载网格。该表包含棒球运动员的名字和击球率。我希望能够使用文本框和按钮按名称搜索,而另一个按钮按击球平均值进行搜索。
答案 0 :(得分:0)
这是我的示例代码。我有一个Textbox
和一个Button
。
Private Sub srchBtn_Click(sender As Object, e As EventArgs) Handles srchBtn.Click
On Error GoTo wewe
If txtSearch.Text = "" Then
Call notFound()
Exit Sub
Else
Dim cantFind As String = txtSearch.Text
SampleBindingSource.Filter = "(Convert(Number_of_Employees, 'System.String') LIKE '" & txtSearch.Text & "') OR (ewan LIKE '" & txtSearch.Text & "') OR (ko LIKE '" & txtSearch.Text & "') OR (sayo LIKE '" & txtSearch.Text & "') OR (hehehe LIKE '" & txtSearch.Text & "')"
If SampleBindingSource.Count <> 0 Then
With DataGridView1
.DataSource = SampleBindingSource
End With
Else
MsgBox(cantFind & vbNewLine & "The search item was not found!", MsgBoxStyle.Information, "Hey boss")
SampleBindingSource.Filter = Nothing
With DataGridView1
.ClearSelection()
.DataSource = SampleBindingSource
End With
End If
End If
hey:
Exit Sub
wewe:
MsgBox("Error Number " & Err.Number & vbNewLine & "Error Description " & Err.Description, MsgBoxStyle.Critical, "Reset Error!")
Resume hey
End Sub
Private Sub reset()
Dim txtS As TextBox = txtSearch
With txtS
.Text = ""
.Select()
End With
If DataGridView1.DataSource Is Nothing Then
Exit Sub
End If
End Sub
Private Sub notFound()
Dim txtS As TextBox = txtSearch
With txtSearch
.Text = ""
.Select()
.SelectAll()
End With
If DataGridView1.DataSource Is Nothing Then
Exit Sub
End If
End Sub
单击按钮可找到特定单词。注意:将该代码放在Button
中。它只能找到拼写正确的单词或整个单词。
示例:您想找到Anthony这个词。输入整个单词,然后单击搜索按钮。
如果您想在不点击任何按钮的情况下搜索某个项目,可以试试这个:
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Try
Using conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Yourdatabase.mdb;")
conn.Open()
Dim command As New OleDbCommand("SELECT * FROM yourtable WHERE (ID like @ID) OR (Sample like @Sample) OR (Sample like @Sample) OR (Sample like @Sample) OR (Sample like @Sample)", conn)
With command.Parameters
.AddWithValue("@Sample", TextBox5.Text)
.AddWithValue("@Sample", TextBox5.Text)
.AddWithValue("@Sample", TextBox5.Text)
.AddWithValue("@Sample", TextBox5.Text)
.AddWithValue("@Sample", TextBox5.Text)
End With
Dim adapter As New OleDbDataAdapter
Dim dt As New DataTable
adapter.SelectCommand = command
adapter.Fill(dt)
DataGridView.DataSource = dt
adapter.Dispose()
command.Dispose()
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR4", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
将该代码放入TextChanged
Textbox
事件中。注意:我使用了连接字符串。
希望这有帮助。