2010-12-10 178 views
0

我拼命嘗試瞭解如何更改winforms dataGridView中單個單元格的背景顏色。我有兩列:如果我更改第二列中的內容,我希望此行第一列中的單元格相應地更改背景。如果他們被漆成如何更改windows.forms.datagrid中單個單元格的背景顏色?

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
    { 
     if (e.ColumnIndex != 0 || e.RowIndex == -1) 
      return; 
     if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "Red") 
      e.CellStyle.BackColor = Color.Red; 
     else 
      e.CellStyle.BackColor = Color.White; 
    } 

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex != 1 || e.RowIndex == -1) 
      return; 
     // dataGridView1.Rows[e.RowIndex].Cells[0]. ??? 
    } 

的第一個事件處理程序設置在第一列的單元格的背景色。如果值更改,第二個事件處理程序應該告訴第一個單元格繪製。如果我改變列的寬度,它會繪製正確的顏色,所以第一個處理程序會完成這項工作。但如何觸發細胞繪畫?

Thanx尋求幫助。

回答

0

我本來以爲編輯會觸發一個重繪,但如果沒有被編輯後運行該事件,那麼你應該能夠迫使這個問題的東西,如:

dataGridView1.InvalidateCell(e.RowIndex, 1); 
+0

這就是我正在尋找的。感謝名單。 – 2010-12-13 07:00:24

0

OK,這裏是不好黑客:

如果我在CellValueChanged事件處理程序插入

var x = dataGridView1.Columns[0].DefaultCellStyle; 
dataGridView1.Columns[0].DefaultCellStyle = null; 
dataGridView1.Columns[0].DefaultCellStyle = x; 

,整個第一列粉刷一新。所以我的細胞也被重新粉刷。但不是很髒,不是嗎?

0

您必須創建一個新的單元格樣式對象,將其設置爲所需的顏色,然後將其應用於當前單元格。

private DataGridViewCellStyle CellStyleGreenBackgnd;

CellStyleGreenBackgnd.BackColor = Color.LightGreen;

dataGridView.CurrentCell.Style.ApplyStyle(CellStyleGreenBackgnd);

0

嘗試這個。

dataGridView1.Rows[indexhere].Cells[indexhere].Style.ForeColor = Color.Yellow; 
相關問題