Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In data grid view for the first 4 row i want to give fore and back color.

The code as follows; i try this code but error shows;
int iRow = 0;
for (int i = 0; i < 4; i++)
{
   datagridView.Rows[iRow].DefaultCellStyle.ForeColor = Color.blue;
   datagridview.rows[iRow].DefaultCellStyle.Backcolor = color.bisque;
   iRow = iRow + 1;
}


when i run error shows as Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.

from my code what is the error.please rectify my mistake from my above code.please help me. i tried bit it is not working.

Thanks;

/Edit Pre tag added by Jibesh
Posted
Updated 13-Jan-13 18:50pm
v2

1 solution

Change your code from

C#
for (int i = 0; i < 4; i++)


To

C#
for (int i = 0; i < datagridView.RowCount; i++)


It looks as though your data grid view has no rows in it and you are making the assumption that there will always be 4 rows. Doing .RowCount will use the number of rows in your data grid view and loop through that, handle any other logic to do first four rows within for loop.

Full snippet

C#
int iRow = 0;
for (int i = 0; i < datagridView.RowCount; i++)
{
datagridView.Rows[iRow].DefaultCellStyle.ForeColor = Color.blue;
datagridview.rows[iRow].DefaultCellStyle.Backcolor = color.bisque;
iRow = iRow + 1;
}
 
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