2016-12-05 71 views
0

我使用foreach循环来检查datagridview中每行的数据,我想避免标题和空buttom行,我该怎么做? 这是我简单的循环:如何循环datagridview全行

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    string datatocheck = row.Cells[2].Value.ToString(); 
    if (datatocheck == "done") 
    { 
     row.Cells[2].Style.ForeColor = Color.Yellow; 
    } 
} 
+0

使用工作循环来代替。 –

+1

'if(!row.IsNewRow)...' – LarsTech

回答

1

在使用迭代器循环中,您可以轻松地跳过第一行和最后一行:

for (int i = 1; i < dataGridView1.Rows.Count() - 1; i++) 
{ 
    string datatocheck = dataGridView1.Rows[i].Cells[2].Value.ToString(); 
    if (datatocheck == "done") 
    { 
     dataGridView1.Rows[i].Cells[2].Style.ForeColor = Color.Yellow; 
    } 
} 

所以开始的“i”为1,而不是0跳过第一行,并确保'我'总是少于总行数减1跳过最后一行。

+0

当我从foreach循环更改为for循环时,'行'不能识别 – Damkulul

+0

检查更新后的代码 - 再次更新。 – Asnivor

+0

是的我改变了它,谢谢你修复你的答案:) – Damkulul

0

使用LINQ,你可以做下一个

var doneRows = dataGridView1.Rows 
          .Cast<DataGridViewRow>() 
          .Skip(1) 
          .Where(row => row.Cells[2].Value.ToString().Equals("done")); 

foreach (var row in doneRows) 
{ 
    row.Cells[2].Style.ForeColor = Color.Yellow; 
} 

或者看来你只能用DataGridViewCell

var doneCells = dataGridView1.Rows 
          .Cast<DataGridViewRow>() 
          .Skip(1) 
          .Select(row => row.Cells[2]) 
          .Where(cell => cell.Value.ToString().Equals("done")); 

foreach (var cell in doneCells) 
{ 
    cell.Style.ForeColor = Color.Yellow; 
}