[英]How to avoid exceptions in utilizing a value of datagridrow when row is not selected
[英]setting the selected row programmatically for a DataGridRow (not by using the index!)
我有一个带有DataGridView
的表单,该表单使用数据适配器( AdsDataAdapter
)从DataSource
填充到表单的Constructor
。 它显示了人们的first name
, surname
和reference 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.