How to change row color in a ListView

Viewed 369

When I read my DataBase values one by one, I made an if statement and I tried to change row color.
For example if fark <= 10.000, my row color is red; if fark < 0 my row color is black.

I wrote the code above and When I execute it gives me error:

InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index

My code:

while (dr.Read())
{
    ListViewItem lv = new ListViewItem(
    dr[0].ToString());
    lv.SubItems.Add(dr[1].ToString());
    lv.SubItems.Add(dr[2].ToString());
    lv.SubItems.Add(dr[3].ToString());
    lv.SubItems.Add(dr[4].ToString());
    listView1.Items.Add(lv);
    fark = Convert.ToDouble(dr[3].ToString()) - Convert.ToDouble(dr[4].ToString());     

    if (fark <= 10.000) 
    {
        MessageBox.Show("Near Maximum ");
        listView1.Items[linemum].BackColor = Color.Red;
    }
    else if (fark <= 20.000 && fark >= 10.000) 
    {
        MessageBox.Show("Maybe Near");
        listView1.Items[linemum].BackColor = Color.Yellow;
    }
    else if (fark < 0) 
    {
      MessageBox.Show("overflow");
      listView1.Items[linemum].BackColor = Color.Black;
    }
    linemum = linemum + 1;
}
1 Answers

Firstly, this code is never executed

else if (fark < 0) 
{
     //
}

because if fark < 0, fark <= 10.000 is true and the statements in this if are executed

Secondly, your exception InvalidArgument=Value of '1' is not valid for 'index' means you want to get an item outside the Items. For example, if there are 1 elements in your Items and you want to get Items[1], it will raise an exception, but Items[0] must work.

Try to init your linemum = 0 before the loop while

Related