如何使用 VB.NET 在 DataGridView 中进行搜索即键入文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31689722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:20:41  来源:igfitidea点击:

How to do a search-as-you-type textbox in a DataGridView using VB.NET

databasevb.net

提问by iamlawrencev

I have connected my DataGridView to a database but I can't implement the search function.

我已将 DataGridView 连接到数据库,但无法实现搜索功能。

The flow of the program would be when I click one column of the DataGridView and I type in the search box, I can only get results from that same column not the other columns beside it.

程序的流程是当我单击 DataGridView 的一列并在搜索框中键入时,我只能从同一列中获取结果,而不能从旁边的其他列中获取结果。

It should also search letter by letter so basically a TextChanged event.

它还应该一个字母一个字母地搜索,所以基本上是一个 TextChanged 事件。

回答by HengChin

This is how i would do it

这就是我要做的

First, to have two variable to store your original datatable from database, and also a string variable to store your selected dgv column headertext (which will be used to do the filter later on).

首先,有两个变量来存储来自数据库的原始数据表,还有一个字符串变量来存储您选择的 dgv 列标题文本(稍后将用于进行过滤)。

Private oriDataTable As New DataTable
Private columnToFilter As String = String.Empty

My test on some dummy data

我对一些虚拟数据的测试

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'dummy datatable
    oriDataTable.Columns.Add(New DataColumn("ID"))
    oriDataTable.Columns.Add(New DataColumn("FirstName"))
    oriDataTable.Columns.Add(New DataColumn("LastName"))
    For i = 0 To 5
        Dim dr As DataRow = oriDataTable.NewRow()
        dr.Item("ID") = i
        dr.Item("FirstName") = "fn type1 " & i
        dr.Item("LastName") = "ln type1 " & i
        oriDataTable.Rows.Add(dr)
    Next
    For i = 6 To 10
        Dim dr As DataRow = oriDataTable.NewRow()
        dr.Item("ID") = i
        dr.Item("FirstName") = "fn type2" & i
        dr.Item("LastName") = "ln type2" & i
        oriDataTable.Rows.Add(dr)
    Next

    'Since you already connected to database 
    'i assume that you could fill a datatable and bind to dgv
    dgvToFilter.DataSource = oriDataTable
    columnToFilter = "ID" 'Assign any default column name
End Sub

Then add a ColumnHeaderMouseClickevent handler on your dgv, update the columnToFiltereach time when user click on it.

然后添加一个ColumnHeaderMouseClick您DGV事件处理程序,更新columnToFilter,每次当它的用户点击。

Private Sub dgvToFilter_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvToFilter.ColumnHeaderMouseClick
    Dim clickedColumn As DataGridViewColumn = dgvToFilter.Columns(e.ColumnIndex)

    'Note:HeaderText must match with your datatable column name
    columnToFilter = clickedColumn.HeaderText
    lblHeaderSelected.Text = columnToFilter
End Sub

And lastly the TextChaged Event. Use the DataTable.Selectmethod to filter the datatable and update the result, if any, to the dgv.

最后是 TextChaged 事件。使用DataTable.Select方法过滤数据表并将结果(如果有)更新到 dgv。

Private Sub txtFilterText_TextChanged(sender As Object, e As EventArgs) Handles txtFilterText.TextChanged
    If txtFilterText.Text.Length <= 0 Then dgvToFilter.DataSource = oriDataTable

    Dim filterString = String.Format("{0} LIKE '{1}%'", columnToFilter, txtFilterText.Text)

    Dim dataRows As DataRow() = oriDataTable.Select(filterString)
    'Choose what you wan to do if no row is found. I bind back the oriDataTable.
    dgvToFilter.DataSource = If(dataRows.Count > 0, dataRows.CopyToDataTable(), oriDataTable)
End Sub

回答by Jake Harry Chavez

You can try this.

你可以试试这个。

 Private Sub txtUname_TextChanged(sender As Object, e As EventArgs) Handles txtUname.TextChanged
    dtaAdap = New SqlDataAdapter("Select * from tbl_user where Fname like '%" & txtUname.Text & "%'" & vbCrLf &
                                 " OR  Lname like '%" & txtUname.Text & "%'", con)
    dt = New DataTable
    dtaAdap.Fill(dt)
    DataGridView1.DataSource = dt
End Sub

The query in SQLAdapter goes a little something like this:

SQLAdapter 中的查询有点像这样:

Select * from <tbl_name> where <firstparametercolumnname> like '%"& <your searchtexboxname.text here> &"%' 
OR <secondparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'

and so on depending on the number of fields you want to look at. Note: "con" is my SQLConnection.

依此类推,具体取决于您要查看的字段数。注意:“con”是我的 SQLConnection。

This whole code snippet will fill your DatagridView with the result of the query everytime the user key in something on your searchtextbox.

每次用户在您的搜索文本框中键入某些内容时,整个代码片段都会用查询结果填充您的 DatagridView。