繁体   English   中英

以编程方式为DataGridRow设置选定的行(不使用索引!)

[英]setting the selected row programmatically for a DataGridRow (not by using the index!)

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

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

我该如何进行导航?

“导航”解决方案

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM