简体   繁体   English

使用文本框(vb.net)在datagridview中的列中搜索

[英]Search through columns in a datagridview using textbox (vb.net)

How do I search through columns in a datagridview using a textbox? 如何使用文本框搜索datagridview中的列? I'm using vb.net 2010. I have a Datagridview with a data source. 我正在使用vb.net2010。我有一个带有数据源的Datagridview。 Below is my code for populating my datagridview. 以下是用于填充datagridview的代码。 The gridview will have 4 columns. 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 textbox and button . 要求 :在我的表单中,我将有一个textbox和一个button The textbox will supply the search string. 文本框将提供搜索字符串。 I need a way to highlight the row when a string is found. 当找到字符串时,我需要一种突出显示行的方法。

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中搜索字符串值?

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 BackColor of the matched rows to Yellow. 上面的代码在Table "Products"的第一列中查找字符串"this" ,并将匹配行的BackColor更改为Yellow。

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. 注意:此答案旨在以通常理解为“在数据源中搜索术语”的方式(即通过依赖查询)来回答OP的问题。 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). 这两个原因解释了为什么我依赖这种方法(以及OP的静音)。 The OP has decided to answer himself what he has considered better. OP已决定回答自己认为更好的问题。 I personally prefer iterative solutions like the one he posted (although I consider that this approach is evident to anyone using a DataGridView ). 我个人更喜欢像他发布的那样的迭代解决方案(尽管我认为这种方法对于使用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). 本说明的重点是强调我不建议您定期使用基于LINQ的方法,只是写了OP明显在寻找的内容(不幸的是,我很难解释一个人的期望,而不是解释清楚寻找的是什么,避免进行任何形式的交流)。

You can use BindingSource for your requirement.So your code will looks like below, 您可以根据需要使用BindingSource 。因此您的代码如下所示,

  • Declare (Public) 声明(公开)

     Dim ds As New DataSet Dim bndSourceGrid As New BindingSource() 
  • Fill dgvProducts with a 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 
  • goto txtboxSerach and on it's TextChanged event 转到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 
  • goto txtboxSerach and on it's Validated event goto txtboxSerach及其经过验证的事件

      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 DataGridView looks like below 我的DataGridView如下所示

      ID Name Other --------------- 0 Abcd 321 1 Abdc 546 2 Bcdsf 1005 


    When I start typing letter A in txtBoxSerach 当我开始在txtBoxSerach中输入字母A

      ID Name Other --------------- 0 Abcd 321 1 Abdc 546 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM