Click here to Skip to main content
14,937,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am working on access based WinForm application. I have colored cell(DateColumn) in my DataGridView. I am trying to count these cell and reflect colored cell No. on a label text. My codes are as follows:

C#
private void metroGrid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {

        if (this.metroGrid1.Columns[e.ColumnIndex].DataPropertyName == "Date 1")
            try
            {
                var EMIDate1 = Convert.ToDateTime(metroGrid1.Rows[e.RowIndex].Cells["date1DataGridViewTextBoxColumn"].Value);


                if (EMIDate1 <= DateTime.Today)
                {
                    e.CellStyle.BackColor = Color.DarkRed;
                    e.CellStyle.ForeColor = Color.White;
                    int countDarkRed = 0;
                    for (int i = 0; i < metroGrid1.RowCount; i++)
                    {
                        if (e.CellStyle.BackColor == Color.DarkRed)
                            ++countDarkRed;
                        labelEMI.Text = "Total EMI due as on today:" + countDarkRed;
                    }
                }
            }
            catch
            {
            }
}


What I have tried:

I tried above code but these codes are counting DataGridView's rows whenever new row is added.It increases no. by 1.
Posted
Updated 27-Mar-19 23:29pm
v2
Comments
Gerry Schmitz 20-Mar-19 10:56am
   
What "logic" are you using to color in the first place? Otherwise, how do you know what colors to look for?
Giorgio Orizio 20-Mar-19 13:53pm
   
The logic he uses is based on the date. If date is past today then it turns DarkRead. As per the code published.
Giorgio Orizio 20-Mar-19 13:55pm
   
I personally would base that count on EMIDate1 instead of the color.

1 solution

Try this:
C#
labelEMI.Text = string.Format("Total EMI due as on today: {0}", metroGrid1.Rows.Cast<DataGridViewRow>()
    .Count(r=>r.Cells["Date 1"].Style.BackColor == Color.DarkRed));
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900