|
-
Nov 4th, 2015, 03:47 AM
#1
Thread Starter
Hyperactive Member
Same background color of rows having same data
Hello
I am trying to change background color of rows in datagridview having same data with this code but am not getting desired results. Can anyone please help?
Code:
Private Sub DataGridView2_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
For i = 0 To DataGridView2.Rows.Count - 1
If i > 0 And i < DataGridView2.Rows.Count Then
If DataGridView2.Rows(i).Cells(0).Value = DataGridView2.Rows(i - 1).Cells(0).Value Then
DataGridView2.Rows(i).DefaultCellStyle.BackColor = Color.WhiteSmoke
Else
DataGridView2.Rows(i).DefaultCellStyle.BackColor = Color.LightGray
End If
End If
Next
End Sub
Thanks
-
Nov 4th, 2015, 10:01 AM
#2
Re: Same background color of rows having same data
Hi,
You are going about this all wrong. The CellFormatting Event is fired for each and every cell of each and every row in the DataGridView and you should therefore not be iterating all the rows of a DataGridView in that Event. What you need to be doing is checking for the current cell index that you want to work with, then checking the previous rows cell index that you want to work with and then do something with that current cell. To do that, have a play with this example:-
vb.net Code:
Private Sub DataGridView1_CellFormatting1(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting If Not DataGridView1.Rows(e.RowIndex).IsNewRow Then If e.ColumnIndex = 0 AndAlso e.RowIndex > 0 AndAlso e.Value.ToString = DataGridView1.Rows(e.RowIndex - 1).Cells(0).Value.ToString Then e.CellStyle.BackColor = Color.Aqua Else e.CellStyle.BackColor = Color.Beige End If End If End Sub
Hope that helps.
Cheers,
Ian
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|