我想找到DataGridView
行中字符串的索引,这是我的代码:
DataGridViewRow row = dgvVisual.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => (string)r.Cells[0].Value == "9");
但row
的返回值为null
而不是DataGridViewRow
,如何解决此问题?
整个代码在这里:
SqlCommand cmd;
cmd = new SqlCommand("select * from MyTable , SqlConnection);
SqlDataReader read;
read = cmd.ExecuteReader();
while (read.Read())
{
int ColIndex= int.Parse(read["ColumnName"].ToString()) + 1;
int RowIndex = -1;
DataGridViewRow row = dgvVisual.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => (string)r.Cells[0].Value == (string)read["ColumnNameB"].ToString().Trim());
if (row != null)
RowIndex = row.Index;
DataGridViewCheckBoxCell chkbxCell = (DataGridViewCheckBoxCell)dgvVisual[ColIndex, RowIndex];
chkbxCell.Value = true;
}
read.Close();
问题解决了,因为数据库中存在一些问题并且回读不正确。
答案 0 :(得分:1)
由于FirstOrDefault()
,它返回null,这意味着它没有在您的查询中找到任何结果。确保您确实拥有具有该条件的任何行。
如果没有看到您的数据,很难说您的lambda查询是否正确。