0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

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 = "" ; 
}
Graffito
  • 1,658
  • 1
  • 11
  • 10
  • I've suggested an edit to address some bugs in your code and also suggested the addition of `theDataGridView.FirstDisplayedScrollingRowIndex = theDataGridView.CurrentCell.RowIndex;` to your *Navigate* method, as it will more visually fulfill the OP's requirement: "*navigate to the first row* [...]". – OhBeWise Jul 21 '15 at 23:18
  • 1
    Setting the selected row as first visible one is perhaps more user friendly. Using lots of DataGridViews, I never did that when selecting the CurrentCell and never had any feedback to display it as first visible row. In the proposed modification, you introduced a "%" between the "LIKE" and the TextBox.text, but I didn't keep it, because the request was rather "StartsWith" than "Contains". – Graffito Jul 21 '15 at 23:32
  • Ah, good catch on the extra `%`, I must have been looking at the other answer when I was testing that in the filter. Sorry about that. – OhBeWise Jul 22 '15 at 14:40