我正在尝试使用以下代码向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在值匹配时显示,但是没有显示行,它只是隐藏了所有行
发布于 2021-10-03 11:05:27
另一个可能的选择是将数据加载到DataTable中,创建一个BindingSource,将BindingSource DataSource属性设置为DataTable。将DataGridView DataSource属性设置为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}'"根据上面的建议,在大多数情况下,处理数据源比处理单元格值要好。
发布于 2021-10-02 17:41:21
当值匹配时,我在IF语句中添加了两个出口,因为它也在搜索每一列,所以它也会导致它们在循环列时被隐藏
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
Nexthttps://stackoverflow.com/questions/69418324
复制相似问题