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.
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
. 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?
You can use BindingSource for your requirement.So your code will looks like below,
Declare (Public)
Fill dgvProducts with a BindingSource
goto txtboxSerach and on it's TextChanged event
goto txtboxSerach and on it's Validated event
Result
my DataGridView looks like below
When I start typing letter
A
in txtBoxSerachHere you have a sample code doing what you want:
The code above looks for the string
"this"
in the first column ofTable "Products"
and change theBackColor
of the matched rows to 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. 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).