在所选索引处选择DataGridViewRow

时间:2011-12-12 20:50:44

标签: c#-4.0 datagridview selectedindex

我在搜索时从DataGridView中选择一行时遇到问题。数据源是来自数据库的DataTable。我使用的搜索框检查DataGridView以查找与产品密钥匹配的产品,如果找到,我想选择它。 这就是我所拥有的:

private void search_btn_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in products_dgv.Rows)
        {
            string tempCode = row.Cells[0].Value.ToString(); //Code comparing
            if (tempCode == code_tb.Text) //Checks if code matchs the search code
            { 
                //I would like to do a products_dgv.selectedIndex = row.Index but it
                //doesnt work
                break;
            }
        }
    }

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用DataGridView的{​​{3}}属性来设置选择。如果您使用FullRowSelect作为选择模式,只需使用您要选择的行中的任何单元格。 例如:

...
if (tempCode == code_tb.Text) //Checks if code matchs the search code
{ 
     products_dgv.CurrentCell = row.Cells[0];
     break;
}
...