2016-03-02 109 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