在给定行值的情况下,如何从datagridview中查找行ID?

有人可以帮我吗?

我必须从1个选定的数组中找到行号,我将其存储在一个单独的数组中并随机地尝试从datagridview获取行号

换句话说:如果我知道datagridview中给定行的列值(例如,对于此行,FirstName ==’Bud’),我如何获得行ID?

您可以使用LINQ查询:

int index = -1; DataGridViewRow row = dgv.Rows .Cast() .Where(r => r.Cells[columnId].Value.ToString().Equals("Some string")) .First(); index = row.Index; 

可能有一些更容易的方法,你以某种方式过滤它,但目前我只能想到循环它。

 int rowIndex = -1; foreach(DataGridViewRow row in DataGridView1.Rows) { if(row.Cells(1).Value.ToString().Equals("mystr")) { rowIndex = row.Index; break; } } // rowIndex is now either the correct index or -1 if not found 

来自: http : //www.vbforums.com/showthread.php?t = 610134

调用BindingSource的Find方法,如果有匹配行,它将返回匹配行的索引。 如果存在,则索引BindingSource以获取该行并更新相应的字段。 如果没有,则调用BindingSource的AddNew方法来创建新行并设置相应的字段。

 //If U Have Add CheckBox To Ur Datagridview int rowIndex = -1; DataGridViewCheckBoxCell oCell; foreach (DataGridViewRow row in dataGridView1.Rows) { oCell = row.Cells[0] as DataGridViewCheckBoxCell; bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value); if (true == bChecked) { rowIndex = row.Index; //ur code } }