使用文本框 (vb.net) 在 datagridview 中搜索列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18782944/
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
Search through columns in a datagridview using textbox (vb.net)
提问by user2059064
How do I search through columns in a datagridview using a textbox? I'm using vb.net 2010. I have a Datagridview with a data source. Below is my code for populating my datagridview. The gridview will have 4 columns.
如何使用文本框搜索 datagridview 中的列?我正在使用 vb.net 2010。我有一个带有数据源的 Datagridview。下面是我用于填充 datagridview 的代码。gridview 将有 4 列。
Private Sub LoadProducts()
Dim CS As String = ConfigurationManager.ConnectionStrings("HRMS.My.MySettings.ResortDBConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(CS)
Dim da As SqlDataAdapter = New SqlDataAdapter("sp_NET_GetProducts_CompanyID", con)
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("@CompanyID", CInt(ConfigurationManager.AppSettings("CompanyID")))
Dim ds As DataSet = New DataSet
da.Fill(ds)
ds.Tables(0).TableName = "Products"
dgvProducts.DataSource = ds.Tables("Products")
dgvProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
dgvProducts.AllowUserToResizeColumns = True
dgvProducts.Refresh()
End Using
End Sub
Requirements: In my form I will have a textboxand button. The textbox will supply the search string. I need a way to highlight the row when a string is found.
要求:在我的表格中,我将有一个textbox和button。文本框将提供搜索字符串。我需要一种在找到字符串时突出显示行的方法。
I don't want to open another connection just to search for a string on a dataset. Is it possible to search for string values directly in the datagridview?
我不想打开另一个连接只是为了在数据集上搜索字符串。是否可以直接在 datagridview 中搜索字符串值?
回答by varocarbas
Here you have a sample code doing what you want:
在这里,您有一个示例代码可以执行您想要的操作:
Dim toSearch As String = "this"
Dim colNum As Integer = 0
Dim res = ds.Tables("Products").AsEnumerable.Where(Function(x) x.Item(colNum).ToString() = toSearch).ToArray
For Each item In res
Dim curRow As Integer = ds.Tables("Products").Rows.IndexOf(item)
dgvSuppliers.Rows(curRow).DefaultCellStyle.BackColor = Color.Yellow
Next
The code above looks for the string "this"in the first column of Table "Products"and change the BackColorof the matched rows to Yellow.
上面的代码查找"this"第一列中的字符串并将匹配行的Table "Products"更改BackColor为黄色。
NOTE: this answer intends to reply the OP's question in the way usually "searching a term in a datasource" is understood, that is, by relying on a query. Also, people tend to prefer solutions involving a lower number of lines. These two reasons explain why I relied on this approach (this together with the OP's muteness). The OP has decided to answer himself what he has considered better. I personally prefer iterative solutions like the one he posted (although I consider that this approach is evident to anyone using a DataGridView). In any case, nothing can be said a priori about which option is more efficient without knowing the exact conditions (size). The whole point of this note is highlighting that I don't recommend relying on LINQ-based approaches on a regular basis, just wrote what the OP was apparently looking for (unfortunately, I am pretty bad at interpreting the expectations of a persons not explaining clearly what is looking for and avoiding any kind of communication).
注意:此答案旨在以通常理解的“在数据源中搜索术语”的方式来回答 OP 的问题,即依靠查询。此外,人们往往更喜欢涉及较少行数的解决方案。这两个原因解释了为什么我依赖这种方法(这与 OP 的静音性一起)。OP 决定回答他自己认为更好的问题。我个人更喜欢像他发布的那样的迭代解决方案(尽管我认为这种方法对于任何使用DataGridView)。在任何情况下,如果不知道确切的条件(大小),就不能先验地说明哪个选项更有效。这篇笔记的重点是强调我不建议定期依赖基于 LINQ 的方法,只是写了 OP 显然在寻找的东西(不幸的是,我很不擅长解释不解释的人的期望清楚地寻找什么并避免任何形式的交流)。
回答by Vivek S.
You can use BindingSourcefor your requirement.So your code will looks like below,
您可以根据您的要求使用BindingSource。所以您的代码将如下所示,
Declare (Public)
Dim ds As New DataSet Dim bndSourceGrid As New BindingSource()Fill dgvProductswith a BindingSource
Private Sub LoadProducts() Dim CS As String = ConfigurationManager.ConnectionStrings("HRMS.My.MySettings.ResortDBConnectionString").ConnectionString Using con As SqlConnection = New SqlConnection(CS) Dim da As SqlDataAdapter = New SqlDataAdapter("sp_NET_GetProducts_CompanyID", con) da.SelectCommand.CommandType = CommandType.StoredProcedure da.SelectCommand.Parameters.AddWithValue("@CompanyID", CInt(ConfigurationManager.AppSettings("CompanyID"))) da.Fill(ds) ds.Tables(0).TableName = "Products" '/*-------------------------------------------- bndSourceGrid.DataSource = ds.Tables("Products") dgvProducts.DataSource = bndSourceGrid '/*-------------------------------------------- dgvProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill dgvProducts.AllowUserToResizeColumns = True dgvProducts.Refresh() End Using End Subgoto txtboxSerachand on it's TextChangedevent
Private Sub txtboxSeracht_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearchCust.TextChanged '/*here "Name" is the column that you want filter/search bndSourceGrid.Filter = String.Format("{0} LIKE '{1}%'", "Name", txtboxSerach.Text) '/* sorting method ascending/descending bndSourceGrid.Sort = "Name ASC" End Subgoto txtboxSerachand on it's Validatedevent
Private Sub txtboxSerach_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtboxSerach.Validated If txtboxSerach.Text = String.Empty Then bndSourceGrid.RemoveFilter() Else bndSourceGrid.Filter = String.Format("{0} = '{1}'", "Name", txtboxSerach.Text) bndSourceGrid.Sort = "Name ASC" End If End Sub
申报(公开)
Dim ds As New DataSet Dim bndSourceGrid As New BindingSource()使用BindingSource填充dgvProducts
Private Sub LoadProducts() Dim CS As String = ConfigurationManager.ConnectionStrings("HRMS.My.MySettings.ResortDBConnectionString").ConnectionString Using con As SqlConnection = New SqlConnection(CS) Dim da As SqlDataAdapter = New SqlDataAdapter("sp_NET_GetProducts_CompanyID", con) da.SelectCommand.CommandType = CommandType.StoredProcedure da.SelectCommand.Parameters.AddWithValue("@CompanyID", CInt(ConfigurationManager.AppSettings("CompanyID"))) da.Fill(ds) ds.Tables(0).TableName = "Products" '/*-------------------------------------------- bndSourceGrid.DataSource = ds.Tables("Products") dgvProducts.DataSource = bndSourceGrid '/*-------------------------------------------- dgvProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill dgvProducts.AllowUserToResizeColumns = True dgvProducts.Refresh() End Using End Sub转到txtboxSerach和它的TextChanged事件
Private Sub txtboxSeracht_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearchCust.TextChanged '/*here "Name" is the column that you want filter/search bndSourceGrid.Filter = String.Format("{0} LIKE '{1}%'", "Name", txtboxSerach.Text) '/* sorting method ascending/descending bndSourceGrid.Sort = "Name ASC" End Sub转到txtboxSerach并在其上进行Validated事件
Private Sub txtboxSerach_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtboxSerach.Validated If txtboxSerach.Text = String.Empty Then bndSourceGrid.RemoveFilter() Else bndSourceGrid.Filter = String.Format("{0} = '{1}'", "Name", txtboxSerach.Text) bndSourceGrid.Sort = "Name ASC" End If End Sub
Result
my DataGridViewlooks like belowID Name Other --------------- 0 Abcd 321 1 Abdc 546 2 Bcdsf 1005
When I start typing letterAin txtBoxSerachID Name Other --------------- 0 Abcd 321 1 Abdc 546
结果
我的DataGridView如下所示ID Name Other --------------- 0 Abcd 321 1 Abdc 546 2 Bcdsf 1005
当我开始A在txtBoxSerach 中输入字母时ID Name Other --------------- 0 Abcd 321 1 Abdc 546

