Click here to Skip to main content
13,001,686 members (93,838 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I have datagridview which is populated with 3 columns partno,locality,houseno. Initially my row colour would be say light blue. Now what i want is whenever houseno changes in row,its row colour should be changed to say grey. That means whenever houseno changes,these two colours should be alternately applied to rows of grid.
For example,values that would be populated in houseno column will be
etc.Now for row with houseno 0 will have row colour as light blue ,for houseno 1 will have row colour grey,for houseno 2 again light blue and so on.
Can any1 help me with this.
Thanks in advance.
Posted 28-Dec-12 20:01pm
Updated 28-Dec-12 21:09pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

There is no direct method that matches your need. You need to add

subscribe the RowAdded event e.g
Color prevBackColor = Color.LightBlue; // Member variable
string prevHouseNumber = string.Empty; // member variable
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
  if (e.RowIndex != -1)
       string houseNumber = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[HOUSE_NUM_COLUMN_INDEX].Value);
      if(prevHouseNumber.Length != 0 && houseNumber != prevHouseNumber)
         //set the alternate color
         if( prevBackColor == Color.Gray)
           prevBackColor = Color.LightBlue; 
         } else if ( prevBackColor == Color.LightBlue)
           prevBackColor = Color.Gray;
         prevHouseNumber = houseNumber;        
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = prevBackColor;
Rachna0309 29-Dec-12 3:01am
but this event would trigger when user changes houseno value.houseno value changes from database itself and row colour should be changed accordingly.
Ashok19r91d 29-Dec-12 3:09am
Mumm my be, Somewhat smart you are, Why you try out that code in your style?
Just Execute these Code Periodically For Example by using Timer...
Rachna0309 29-Dec-12 3:11am
Can you provide me code for that?
Ashok19r91d 29-Dec-12 3:12am
VB or C#?
Ashok19r91d 29-Dec-12 3:20am
Question Improved...
Now you need to Display like Alternating Rows, But the Problem is there may be more than one row for each housenumber... Am I Right?
jibesh 29-Dec-12 3:20am
No timer is not a good idea since we already have a better way to solve. Timer will make the whole logic mess and you need to write lot of code to handle that.
Ashok19r91d 29-Dec-12 3:21am
I agree...
Ashok19r91d 29-Dec-12 3:10am
jibesh 29-Dec-12 3:19am
this would trigger when the cell content changes no matter how the changes occurred whether user modified or changed by databinding. try running this code and see.
Rachna0309 29-Dec-12 3:13am
Rachna0309 29-Dec-12 3:31am
Ashok19r91d:yes there would be more than 1 row for each housenumber.
jibesh 29-Dec-12 3:35am
The above code will work for you not matter how many rows are there. all you need to do is get the cell content value for the column that matches the house number and update the Row color for the row that matching e.RowIndex
Rachna0309 29-Dec-12 3:42am
Can you please put down this in code form..
jibesh 29-Dec-12 3:57am
Solution updated to handle the initial row loading.
Ashok19r91d 29-Dec-12 5:31am
Look for ma Solution, Accept solution if it help you in any way...
Rachna0309 29-Dec-12 3:33am
jibesh:I tried your code but not working. datagridview loads initially and then if I change column value then only cellvaluechanged event is called.
Rachna0309 29-Dec-12 4:06am
I can't hard code houseno value...It can have many other values.How can I compare current datagridview row with previous one?
jibesh 29-Dec-12 4:17am
its not the house number from the database what I meant was the column/cell index that represents the house number. I modified the value with HOUSE_NUM_COLUMN for better understanding.
Rachna0309 29-Dec-12 4:34am
int data = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[HOUSE_NUM_COLUMN_INDEX].Value);
This line would return houseno value from database.And you are telling me to compare this value with 0,1 etc.Dats not possible.
jibesh 29-Dec-12 4:42am
why not ? thats what you want. row color based on the house number. what's the problem in that?
Rachna0309 29-Dec-12 4:48am
houseno can also have value "1à10" ,"1à37" etc.If I will use above code then I will have to compare all database values.
jibesh 29-Dec-12 4:54am
that sounds like each row will be of different color. now answer my following questions.

1.who and from where the color for each row gets decided? you said for house value x the color should be x1 for y its y1 etc. there any lookup table that defines the color for each house number?

Rachna0309 29-Dec-12 5:00am
my datagridview gets populated through dataset.
I want to use only two colours. There is no lookup table that defines colour. When datagrid is getting filled,for 1st house number(say 0) its color should be say x1,next house number(say 1),it should be y1,again when house number changes(say 2),it should be again x1.
jibesh 29-Dec-12 5:11am
you want to set the alternate colors for the rows in the gridview right? if thats the case its even more simple datagridview already has this facility.

set your preferred backColor for your alternate rows using the following prorperties
this.dataGridView1.AlternatingRowsDefaultCellStyle &

Solution also updated.
Rachna0309 29-Dec-12 5:20am
I think you are not reading my question number 0 value can have 3 records..for these three records it should be same colour.your updated solution wont give this will colour alternate rows.
jibesh 29-Dec-12 5:37am
Ok I get it now. sounds like you need to add some logic to control the color there is not direct method to control the color that matches your need.
may be you can do the following steps in rowAdded event
start with bkColor as Light Blue.
Check the House number of the first row and set the BackColor as LighBlue
And store this house number in a local variable.
RowAdded event is called second time to add next rows
check the current house number and prev store house number
if it matches use LightBlue it not change the Color as Gray

do you want me to write the code? let me know if you want the sample.
Rachna0309 29-Dec-12 5:39am
Yes give me sample for this.
jibesh 29-Dec-12 5:48am
Please check the sample code. give a try and let me know is that helps.
Rachna0309 29-Dec-12 6:24am
When datagridview loads for first time,I get error "Argument out of range exception." at below line:
string houseNumber = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[HOUSE_NUM_COLUMN_INDEX].Value);
jibesh 29-Dec-12 6:35am
Please dont copy paste the whole code what we put here is merely a sample code we dont know about your code and the variables, datatypes you have used. so just take the logic and apply that in your application.

you need to use proper datatype to convert data inside the cell to a local variable also do check the cell index, row index etc.

you will get this exception when you try to access an array whose index is above the array count/length. Please be note that array index starts from 0 so the index you use must be within the array length.
Rachna0309 29-Dec-12 7:03am
ok thanks...its working now.
jibesh 29-Dec-12 7:05am
Great. Happy to hear that your problem is resolved. If my solution helped to solve the problem you can mark the solution as resolved so that others see the solution for later use.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

If your Rows are Ordered by HouseNumber then this Code Help you
Private Sub FormatGrid()
Dim j as Integer = -1
Dim Colr As Color
'Here I assume that HouseNumber available in Cell (0) (i.e., First Column)
For i = 0 To DataGridView1.RowCount - 1
    If DataGridView1.Rows(i).Cells(0).Value <> j Then
        j = DataGridView1.Rows(i).Cells(0).Value
        Select Case Colr
        Case Gray: Colr = LightBlue
        Case LightBlue: Colr = Gray
        End Select      
    End If
    DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color  
End Sub
Ashok19r91d 29-Dec-12 5:42am
Call this Function FormatGrid When ever you need to Refresh Your DataGrid...
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Add below code in DataGridView's DataBindingComplete event:

private void dgvListData_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
Color firstColor = Color.White, secondColor = ColorTranslator.FromHtml("#C8DFF1"), prevBackColor = ColorTranslator.FromHtml("#C8DFF1"); // Member variable
string prevVoucherNumber = string.Empty; // Member variable

foreach (DataGridViewRow dRow in dgvListData.Rows)
#region < To give alternate row color based on Voucher No >
if (dRow.Index != -1)
string voucherNumber = Convert.ToInt32(dgvListData.Rows[dRow.Index].Cells["Voucher_No_With_Prefix"].Value).ToString();

if (prevVoucherNumber.Length == 0 || voucherNumber != prevVoucherNumber)
//set the alternate color
if (prevBackColor == firstColor) // firstColor
prevBackColor = secondColor; // secondColor
else if (prevBackColor == secondColor) // secondColor
prevBackColor = firstColor; // firstColor
prevVoucherNumber = voucherNumber;

dgvListData.Rows[dRow.Index].DefaultCellStyle.BackColor = prevBackColor;


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170624.1 | Last Updated 1 Aug 2015
Copyright © CodeProject, 1999-2017
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