DataGridView实时搜索数据



我正在尝试使用此代码在vb.net中添加一个搜索功能到DataGridView

For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next

当值匹配时,我看到MsgBox显示,但是行没有显示,它只是隐藏所有行

另一种可能的选择是将数据加载到DataTable,创建BindingSource,将BindingSource DataSource属性设置为DataTable。设置DataGridViewDataSource属性为BindingSource

下面的示例针对DataTable中的一个列。如果用户清除TextBox,则过滤器将被删除,而如果存在带有修剪的文本过滤器

Private Sub SearchButton_Click(sender As Object, e As EventArgs) _ 
Handles SearchButton.Click
If String.IsNullOrWhiteSpace(SearchTextBox.Text) Then
bindingSource.Filter = ""
Else
Dim currentRowCount = bindingSource.Count
bindingSource.Filter = $"TRIM(LastName) = '{SearchTextBox.Text}'"
MessageBox.Show($"Before: {currentRowCount} Now: {bindingSource.Count}")
End If
End Sub

编辑如果列名可能是可变的,请考虑加载带有列名的ComboBox,然后按如下方式调整代码。

bindingSource.Filter = $"TRIM({FilterComboBox.Text}) = '{SearchTextBox.Text}'"

根据上面的建议,在大多数情况下,使用数据源比使用单元格值更好。

当值匹配时,我在IF语句中添加了2个出口,因为它正在搜索每个列,所以它导致它们被隐藏,因为它循环列也

For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next

相关内容

  • 没有找到相关文章

最新更新