2012-08-06 19 views
0

我想找到一個字符串的指數在DataGridView行,這裏是我的代碼:查找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

不明白你的問題。這會給你一個連續的。 – nunespascal 2012-08-06 07:12:13

+0

我會修改問題 – User2012384 2012-08-06 07:13:55

+0

已修改,已更改索引爲DataGridViewRow – User2012384 2012-08-06 07:16:26

回答

1

由於FirstOrDefault()它返回null,這意味着它沒有找到任何與您的查詢結果。確保您確實有任何具有該條件的行。

沒有看到你的數據很難說如果你的lambda查詢是正確的。

+0

我檢查了datagridview中有行 – User2012384 2012-08-06 07:49:25

+0

請提供您的數據示例:例如,您認爲行將滿足您的查詢條件。 – STiLeTT 2012-08-06 08:01:45

+0

預期結果:row.Index = 8(string)read [「ColumnNameB」]。ToString()。Trim()= 8 – User2012384 2012-08-06 08:05:23