Searching a datagridview

redgar

Member
Joined
Feb 28, 2008
Messages
13
Programming Experience
3-5
I found some code about multiple ways to search datagridviews. I found one that was very nice and simple but the row it selects through the search has nothing to do with the text in my search textbox. Its very strange. Id really like to figure out what my problem is and go with this method as it seems I'm pretty close to getting it working.

Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim dt As DataTable = dataSet.Hospital_Table
Dim dr() As DataRow = dt.Select("hospname LIKE '" + txtSearch.Text + "%'", "hospname")
If (dr.GetUpperBound(0) >= 0) Then
dt.DefaultView.Sort = "hospname"
HospitalTableBindingSource.Position = dt.DefaultView.Find(dr(0)("hospname").ToString())
End If

I have the dataset, datatable and bindingsource already generated for the form. I created the instance datatable dt to cut down on the long names.

Like I said, the problem is when I type in my txtSearch textbox it does select different rows in my table using the bindingsource position, but they just dont correspond to the text in the search box. Is my sql .select statement messed up or something? I got it straight from the code found here... http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=844725&SiteID=1 To note, I'm not using a sql database. My adapters etc are therefore oledb.

Help appreciated!

redgar
 
Last edited:
Lol, figured it out although I don't totally understand what happened.

I added:

Dim bs As BindingSource = HospitalTableBindingSource
bs.DataSource = dt.DefaultView

... It seems I mostly just set my bindingsource.datasource to my tables "defaultview". I of course changed the rest to

Dim dr() As DataRow = dt.Select("hospname LIKE '" + txtSearch.Text + "%'", "hospname")
If (dr.GetUpperBound(0) >= 0) Then
dt.DefaultView.Sort = "hospname"
bs.Position = dt.DefaultView.Find(dr(0)("hospname").ToString())
End If

... and it worked.

What exactly does changing the source to my datatable.defaultview do?
 
You dont seem to have made the logical conenction that searching for a row in a datatable, and then setting the position of a view (which is sorted) to that index, wont give you the right row


a
g
z
t

find Z
it is at row 3

set the position of a sorted list, to 3:

a
g
t
z

T is shown, because T is in position 3


You might have better luck (more logical) if you forget the defaultview, and set the .Filter of the bindingsource instead. that way only rows that match will be shown
 
Back
Top