计算datagrid中的行颜色

时间:2015-04-13 18:16:00

标签: c# winforms datagridview

这是我的代码我应该怎么做..?我使用颜色的行,并希望标签14,16中的颜色类型数量,我尝试了很多代码,但没有工作

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        var now = DateTime.Now;
        var expirationDate = DateTime.Parse(row.Cells[6].Value.ToString());
        var sevenDayBefore = expirationDate.AddDays(-3);
        label12.Text = Convert.ToString(dataGridView1.Rows.Count);

        if (now > sevenDayBefore && now < expirationDate)
        {
         label14.Text = (what i type here to count yellow)
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
        else if (now > expirationDate)
        {
            label16.Text = (what i type here to count red)            
            row.DefaultCellStyle.BackColor = Color.Red;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

试试这个:

public void CountRowColor()
    {
        int red = 0, yellow = 0;

        foreach(DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.DefaultCellStyle.BackColor == Color.Red)
                red++;
            if (row.DefaultCellStyle.BackColor == Color.Yellow)
                yellow++;
        }

        this.label14.Text = yellow.ToString();
        this.label16.Text = red.ToString();
    }