2016-12-05 27 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; 
}