2009-11-24 82 views

回答

2
foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    if (row.Cells[0].Value.ToString() == "someVal") 
    { 
     row.DefaultCellStyle.BackColor = Color.Tomato; 
    } 
} 
+0

謝謝u.I'm剛剛分配datasource.So,這段代碼也應包括分配數據源後。對? – Nila 2009-11-24 11:54:56

+0

是的,你應該在分配數據源之後執行此操作 – 2009-11-24 12:07:47

0

設置默認的單元格樣式會着色整行。爲單個行設置默認值聽起來像是一個壞主意。您需要一個else語句來處理那些不屬於默認cellstyle設置爲「someVal」的行,而不是讓它們像其他顏色一樣着色,因爲它們不採取任何行動。此外,類型轉換爲Value的實際類型應該會比ToString()提供更好的性能。我可以想象,這可能會在每次更新的整個列表中循環。

相反,只是着色一個單細胞,像這樣做:

foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    if ((string)row.Cells[0].Value == "someVal") 
    { 
     row.Cells[0].Style.BackColor= Color.Tomato; 
    } 
} 
1

CellFormatting事件網格可以檢查值,它們將被顯示,並相應地更改CellStyle

您可以使用事件參數的RowIndexColumnIndex屬性來檢查要顯示哪個單元格。當需要更改屬性時,您可以設置CellStyle屬性(例如e.CellStyle.ForeColor = Color.Red;)。

0

如果您只想更改當前選定的單元格。

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 

     grid1.CurrentCell.Style.SelectionBackColor = Color.Red; 


    } 
相關問題