Click here to Skip to main content
15,890,391 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
protected void OnRowDataBound123(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell statusCell1 = e.Row.Cells[1];
        if (statusCell1.Text != "-")
        {
            string[] a = statusCell1.Text.Split('/');
            if (a[0] != a[1])
            {
                statusCell1.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}


i'm using this function in gridview onrowdatabound ,if data before and after / is not match then red color text.
my sample data :
5/6
11/11
-
1/3


but keep getting error :
C#
System.IndexOutOfRangeException: Index was outside the bounds of the array.


What I have tried:

C#
protected void OnRowDataBound123(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell statusCell1 = e.Row.Cells[1];
        if (statusCell1.Text != "-")
        {
            string[] a = statusCell1.Text.Split('/');
            if (a[0] != a[1])
            {
                statusCell1.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}
Posted
Updated 26-Oct-16 20:15pm
v2

Hello ,
Just check the length of the array returned in your if statement .
 string[] a = statusCell1.Text.Split('/');
if(a.Length > 1)
{
//do other stuff
}

the exception comes as returning array of size less than the index you are accessing with.
Here you are accessing the array element 1 then there must be atleast 2 elements in the array as array index starts with 0 .
Thanks
 
Share this answer
 
That could be because you have one or more entries which is not in the desired format.
Just add a check for you go ahead to compare.
Something like-
C#
if(a.Length>1)
{
   if (a[0] != a[1])
   {
      statusCell1.ForeColor = System.Drawing.Color.Red;
   }
}


You could also put a watch on the values while debugging to see what are the values you are getting.

Hope, it helps :)
 
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