Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to hide a row if the cell says 'processing'


private void MainSystem_Load(object sender, EventArgs e)
{

foreach (DataGridViewRow dr in dataGridView4.Rows)
{
if (dr.Cells[7].Value.ToString() == "Processing")
{
dr.Visible = false;
}
}
}

But I'm getting an error message when I run it of ...

'An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.'

However when I change the 'cells[]' number to a smaller number the program runs but it without the code working.

What I have tried:

Re-writing code, changing the 'cells[]' number
Posted
Updated 6-Dec-17 16:30pm

1 solution

Quote:
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.'

The error clearly says that you are trying to access an index in the collection which is not present.
In c# most of the collections works on zero based index, if you are trying to access the 7th column in the datagridview then you will have to provide the index value as 6.
You shall validate as below

foreach (DataGridViewRow dr in dataGridView4.Rows)
           {
               int targetColumnIndex = 6;
               if (dr.Cells.Count > targetColumnIndex)  // validate the index
                   if (dr.Cells[targetColumnIndex].Value.ToString() == "Processing")
                   {
                       dr.Visible = false;
                   }
           }
 
Share this answer
 
v2

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