【发布时间】:2020-07-27 07:38:33
【问题描述】:
我正在尝试在我的项目中实现与 ctrl+F 功能等效的功能。我希望它像在 excel 中一样工作,其中光标指向任何单元格中的匹配字符串。它也可以用作过滤器,只显示具有匹配字符串的行。
编辑 1:这是我在使用 @Gabriel Stancu 的方法时尝试过的:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Dim search As New OleDbCommand
'Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim dgv As DataGridView
Dim searchedValue As String
frmPrinc.dgv.DataSource = dt.DefaultView
searchedValue = txtBoxName.Text
MsgBox(searchedValue) 'Displayed
For Each row As DataGridViewRow In frmPrinc.dgv.Rows
MsgBox("yes") 'Not displayed
For Each cell As DataGridViewCell In row.Cells
MsgBox("yes2") 'Not displayed
If cell.Value IsNot DBNull.Value Then
MsgBox("yes3") 'Not displayed
If cell.Value.ToString().Equals(searchedValue) Then
cell.Selected = True
MsgBox(cell.Selected)
Exit Sub
End If
End If
Next
Next
End Sub
这刚刚清除了我的 DataGridView 显示
编辑 2:这是我目前正在使用 @jmcilhinney 的方法进行的工作:
Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
Dim myBindingSource As New BindingSource
Dim myDataTable As New DataTable
Dim myDataGridView As New DataGridView
myBindingSource.DataSource = myDataTable
myDataGridView.DataSource = myBindingSource
Dim myValue As String
myValue = txtBoxName.Text
MsgBox(myValue)
myDataTable.Columns.Add(New DataColumn("NAME", GetType(String)))
myBindingSource.DataSource = myDataTable
myBindingSource.Position = myBindingSource.Find("NAME", myValue) 'Running fails on this line
'myBindingSource.Filter = $"MyColumn LIKE '%{myValue}% OR MyOtherColumn LIKE '%{myValue}%'"
Dim sourceRows = myBindingSource.Cast(Of DataRowView)().
Where(Function(drv) CStr(drv("NOM")).Contains(myValue)).
ToArray()
For Each gridRow As DataGridViewRow In myDataGridView.Rows
gridRow.Selected = sourceRows.Contains(DirectCast(gridRow.DataBoundItem, DataRowView))
Next
End Sub
以上内容仍在进行中,但我有点卡住了
System.ArgumentException : 'DataMember property' NAME 'could not be found in the DataSource.'
【问题讨论】:
-
根据您实际描述的内容,该代码绝对没有意义。一方面,如果您尝试执行查询,为什么要调用
ExecuteNonQuery?如果您尝试在DataGridView中实现 Find 函数,那么这意味着您已经拥有一个填充的DataGridView,但情况似乎并非如此,因此您应该学习首先如何做到这一点。首先了解如何执行查询,然后了解如何使用该查询的结果填充DataGridView。完成这两件事后,也许您可以考虑在本地搜索该数据。 -
对不起,如果我没有说清楚,但是是的,我刚刚开始学习,我已经有一个填充的 DataGridView,我只是强调我尝试过的内容,我明白这没有任何意义.这就是为什么我要寻求帮助才能做到这一点。
标签: vb.net search filter datagridview ms-access-2003