Home > Back-end >  Highlight multiple rows from a listbox based on two if condition in C#
Highlight multiple rows from a listbox based on two if condition in C#

Time:01-13

I need to highlight in red the expiry dates which is due in 30 days. And highlight in yellow the dates which is lower than today. My program highlight just first row. I think I am wrong at the for loop. This is my code:

string dateInString = con.read["Data_expirare"].ToString();

DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);

for (int i = 0; i <= listBox1.Items.Count; i  )
{
    if (DateTime.Now >= expiryDate)
    {
        listView1.Items[i].BackColor = Color.Red;
    }
    if (DateTime.Now > startDate)
    {
        listView1.Items[i].BackColor = Color.Yellow;
    }
}

This is what my program return:

enter image description here

CodePudding user response:

Swap the checks:

string dateInString = con.read["Data_expirare"].ToString();

DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);

for (int i = 0; i < listBox1.Items.Count; i  )
{
    if (DateTime.Now > startDate)
    {
        listBox1.Items[i].BackColor = Color.Yellow;
    }
    if (DateTime.Now >= expiryDate)
    {
        listBox1.Items[i].BackColor = Color.Red;
    }
}

CodePudding user response:

I try this, just red color without yellow:

for (int i = 0; i < listView1.Items.Count; i ) {

                DateTime x = Convert.ToDateTime(listView1.Items[i].SubItems[1].Text);
                DateTime y = x.AddDays(30);
               /* if (DateTime.Now > x)
                {
                    listView1.Items[i].BackColor = Color.Yellow;

                }*/
                if (DateTime.Now >= y)
                {
                    listView1.Items[i].BackColor = Color.Red;

                }
            }
  •  Tags:  
  • Related