2015-02-10 134 views
0

我已经通过Visual Studio IDE设置了AlternatingRowStyle BackColor,我的问题是,如果我根据某些条件修改了单元格的BackColor,我该如何将它“取消设置”为正确的行颜色(即白色或交替行颜色),而不诉诸RowIndex的模。使用DataGridView恢复交替行颜色

我试图与明显成功以下,但我不是100%,如果是这样的解决方案:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     double d = Convert.ToDouble(e.Value); 

     if (d > 5) 
     { 
      e.CellStyle.BackColor = Color.Red; 
     } 
     else 
     { 
      e.CellStyle.ApplyStyle(dataGridView1.RowsDefaultCellStyle); 
     } 
    } 
+0

什么是明显的成功?你打算准确达到什么? – chouaib 2015-02-10 02:41:35

+0

基本上,如果一个奇数行(如Color.White)由于条件而被设置为红色,当它不再符合条件时,它将被设置为白色。并且,当偶数行(如Color.Yellow)由于条件而设置为红色时,如果不再满足条件,则会将其设置为黄色。通过显而易见的成功,我的意思是它似乎有效,但我没有机会广泛测试,并试图找出是否有更好的方法。我试过搜索,但很难说 – Tony 2015-02-10 02:54:44

回答

0

你应该使用DataGridViewCellPainting,编辑CellStyleDataGridViewCellPaintingEventArgs

看来,e.CellStyle实际上并不影响cell.CellStyle,这意味着如果条件不符合,则不需要重置单元格

0

因为您决定了backColor根据它们的值,我建议你使用CellValueChanged事件。

我假定奇数行,是黄色的和甚至行是通过默认的白色,在情况下,任何小区满足条件(值> 5)这将是以红色显示。

private void dataGridView1_CellValueChanged(object sender,DataGridViewCellEventArgs e) 
{ 
    int col = e.ColumnIndex; 
    int row = e.RowIndex; 
    double d = Convert.ToDouble(dataGridView1[col, row].Value); 

    switch (row%2) 
    { 
     case 0: 
      if (d > 5) 
       dataGridView1[col, row].Style.BackColor = Color.Red; 
      else 
       dataGridView1[col, row].Style.BackColor = Color.White; 
     break; 
     case 1: 
      if (d > 5) 
       dataGridView1[col, row].Style.BackColor = Color.Red; 
      else 
       dataGridView1[col, row].Style.BackColor = Color.Yellow; 
     break; 
    } 
}