2010-12-10 166 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; 
相关问题