Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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 13-Jan-13 15:35pm
Edited 13-Jan-13 18:50pm
Jibesh16.6K
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Change your code from
 
for (int i = 0; i < 4; i++)
 
To
 
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
 
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;
}
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 14 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100