2016-03-02 60 views
0

这是我的代码,它应该显示2015年的红色数据和2016年的绿色数据。但不工作?我的DataGridView不改变它的颜色?

enter image description here

private void changecolor() 
{  
    foreach (DataGridViewRow rows in dgvExpense.Rows) 
    { 
     DateTime dates = (DateTime)rows.Cells[2].Value; 

     if (dates.Year == 2015) 
     { 
      rows.DefaultCellStyle.BackColor = Color.Red; 
     } 
     else if (dates.Year == 2016) 
     { 
      rows.DefaultCellStyle.BackColor = Color.Green; 
     } 
    } 
} 
+3

你如何称这种'changecolor'方法?它不应该是'Cells [3]'而是? –

+0

非常感谢你,我没有打电话给他,这是为什么它没有工作。再次感谢你 –

回答

0

因为索引从0开始,你应该使用Cells[3]。 您的代码将如下所示:

private void changecolor() 
{  
    foreach (DataGridViewRow rows in dgvExpense.Rows) 
    { 
     DateTime dates = (DateTime)rows.Cells[3].Value; 

     if (dates.Year == 2015)) 
      rows.DefaultCellStyle.BackColor = Color.Red; 
     else if (dates.Year == 2016) 
      rows.DefaultCellStyle.BackColor = Color.Green; 
    } 
} 
+0

即使它会以'1'作为起始索引,它将成为'Cells [4]'而不是'Cells [2]':) –

+0

你显然是对的,只是想指出它... – Marcel