2015-07-21 25 views
0

我使用数据适配器(AdsDataAdapter)在表单上使用DataGridView填充表单的ConstructorDataSource。它显示人们的first namesurnamereference number(这是数据库中基础表的主键)。然而,DataGridView中的行由surname字段排序(通过使用传递到数据适配器的SELECT语句中的ORDER BY子句)。以编程方式为DataGridRow设置选定的行(不通过使用索引!)

DataGridView被填充后,我希望能够输入一个TextBox一个surname,并有DataGridView定位到第一行,其中surname的第一个字母匹配什么类型的用户。

我该如何去做这个导航?

+0

@ user5129991:你知道,你可以选择你的问题的答案? – CharithJ

回答

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

“过滤器” 的解决方案

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

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

然后设置的BindingSource的TextChanged事件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 = "" ; 
} 
+0

我建议编辑来解决代码中的一些错误,并且还建议在* Navigate *方法中添加'theDataGridView.FirstDisplayedScrollingRowIndex = theDataGridView.CurrentCell.RowIndex;',因为它将更直观地满足OP的要求:“ *导航到第一行* [...]“。 – OhBeWise

+1

将选定的行设置为第一个可见的行可能对用户更友好。使用大量的DataGridViews,我从来没有这样做过,当选择CurrentCell时,从来没有任何反馈将它显示为第一个可见行。在提议的修改中,您在“LIKE”和TextBox.text之间引入了一个“%”,但我没有保留它,因为请求比“Contains”更为“StartsWith”。 – Graffito

+0

啊,对额外'%'有很好的理解,当我在过滤器中测试时,我一定在看另一个答案。对于那个很抱歉。 – OhBeWise

相关问题