简体   繁体   English

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

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

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 ). 我有一个带有DataGridView的表单,该表单使用数据适配器( AdsDataAdapter )从DataSource填充到表单的Constructor It shows people's first name , surname and reference number (which is the primary key of the underlying table in the database). 它显示了人们的first namesurnamereference number (这是数据库中基础表的主键)。 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). 但是, DataGridView的行按surname字段排序(通过使用传递到数据适配器的SELECT语句中的ORDER BY子句)。

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

How do I go about doing this navigation? 我该如何进行导航?

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将DataTable绑定到DataGridView。

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

Then set the Filter property of the BindingSource in the TextChanged event: 然后在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