以编程方式为DataGridRow设置所选行(而不是使用索引!)

时间:2015-07-21 20:20:50

标签: c# datagridview datagridviewrow

我有一个带有DataGridView的表单,使用数据适配器(Constructor)从DataSource填写表单AdsDataAdapter 。它显示了人们first namesurnamereference number(这是数据库中基础表的主键)。然而,DataGridView中的行由surname字段排序(通过使用传递给数据适配器的ORDER BY语句中的SELECT子句。)

填充DataGridView后,我希望能够在surname中输入TextBox,并让DataGridView导航到第一行surname的字母与用户输入的内容相匹配。

如何进行此导航?

1 个答案:

答案 0 :(得分:1)

“导航”解决方案

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 ;
    }
  }
}

“过滤器”解决方案

首先,通过BindingSource将DataTable绑定到DataGridView。

BindingSource theBindingSource = new BindingSource() ;
theBindingSource.DataSource    = theDataTable ;
theDataGridView.DataSource     = theBindingSource ;

然后在TextChanged事件中设置BindingSource的Filter属性:

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 = "" ; 
}
相关问题