“导航”解决方案
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 = "" ;
}