Click here to Skip to main content
15,867,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
so that if it is more than 2, the text color of two cells will change

but error

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'


What I have tried:

con.Open();
           Query = "select Entry_Date,Received_Date from tblSaleServices";
           SqlCommand cmd = new SqlCommand(Query, con);
           SqlDataReader sdr = cmd.ExecuteReader();

           if (e.ColumnIndex == 0 & e.Value != null)
           {
               while (sdr.Read())
               {
                   DateTime entry = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[10].Value);
                   DateTime received = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[11].Value);

                   TimeSpan value = received.Subtract(entry);
                   int val = Convert.ToInt32(value.Days);

                   if (val > 2)
                   {
                       e.CellStyle.ForeColor = Color.Red;
                   }

               }
           }

           con.Close();
Posted
Updated 29-Jul-22 3:02am

1 solution

Arrays in C# are zero based, and so the only valid values you can use for an index has to be between 0 and (N - 1) where N is the number of items in the array. Any other value (i.e. negative, or greater-than-or-equal to N) will give you an "index out of range" exception.
So for an array with three elements, the only valoid index values are 0, 1, and 2.

We don't know exactly where your index error is being thrown, but I suggest that this line might be relevant:
if (e.ColumnIndex == 0 & e.Value != null)
& is a binary AND operator, not the logical AND which is &&
Binary AND compares bits in a number, and returns all the bits that are the same.
Logical AND compares boolean values, and returns true if and only if both parameters are true.
 
Share this answer
 

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