0

On form load event when I load data in datagridview after that I call this function to change color of those rows in which the paid expense is Yes but it gives me nullreference exception on the line

PaidStatus = ExpensesDataGridView.Rows[i].Cells[4].Value.ToString();

public void ExpenseRowColor()
    {
        int i;
        string PaidStatus;

        for (i = 1; i <= ExpensesDataGridView.Rows.Count; i++)
        {
            PaidStatus = ExpensesDataGridView.Rows[i].Cells[4].Value.ToString();

            if (PaidStatus == "Yes")
            {
                ExpensesDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
    }
Aizaz hussain
  • 29
  • 1
  • 11

1 Answers1

0

Cells start from a 0th index, meaning that the 4th cell would be at [3] index . In the same way, the row and column indices start from 0 as well but your loop starts from an int i = 1 so I suggest you change that as well to: for (i = 0; i < ExpensesDataGridView.Rows.Count; i++){}

Or use foreach :

 foreach (DataGridViewRow row in ExpensesDataGridView)
 { 
     //use row here
 }
Afnan Makhdoom
  • 666
  • 8
  • 19