Reputation: 1
I have a form with a DataGridView
on it, that gets populated in the form's Constructor
from a DataSource
using a data adapter (AdsDataAdapter
). It shows people's first name
, surname
and reference number
(which is the primary key of the underlying table in the database). The rows in the DataGridView
however are ordered by the surname
field (by using the ORDER BY
clause in the SELECT
statement that gets passed to the data adapter).
After the DataGridView
is populated, I want to be able to type a surname
in a TextBox
, and have the DataGridView
navigate to the first row where the first letters of the surname
matches what the user types.
How do I go about doing this navigation?
Upvotes: 0
Views: 110
Reputation: 1718
The "navigate" solution
private void textBox1_TextChanged(object sender, EventArgs e)
{
for (int i=0;i<theDataGridView.RowCount;i++)
{
if (theDataGridView.Rows[i].Cells["surname"].Value.ToString().StartsWith(textBox1.Text))
{
theDataGridView.CurrentCell = theDataGridView.Rows[i].Cells["surname"];
// optionally
theDataGridView.FirstDisplayedScrollingRowIndex = theDataGridView.CurrentCell.RowIndex;
break ;
}
}
}
The "Filter" solution
First, bind your DataTable to the DataGridView via a BindingSource.
BindingSource theBindingSource = new BindingSource() ;
theBindingSource.DataSource = theDataTable ;
theDataGridView.DataSource = theBindingSource ;
Then set the Filter property of the BindingSource in the TextChanged event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
theBindingSource.Filter = "surname LIKE '"+textBox1.Text+"%'";
// if no match : Cancel filter
if (theDataGridView.RowCount==0) theBindingSource.Filter = "" ;
}
Upvotes: 1