Results 1 to 2 of 2

Thread: Same background color of rows having same data

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Posts
    362

    Question 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

  2. #2
    Frenzied Member IanRyder's Avatar
    Join Date
    Jan 2013
    Location
    Healing, UK
    Posts
    1,232

    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:
    1. Private Sub DataGridView1_CellFormatting1(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    2.   If Not DataGridView1.Rows(e.RowIndex).IsNewRow Then
    3.     If e.ColumnIndex = 0 AndAlso e.RowIndex > 0 AndAlso e.Value.ToString = DataGridView1.Rows(e.RowIndex - 1).Cells(0).Value.ToString Then
    4.       e.CellStyle.BackColor = Color.Aqua
    5.     Else
    6.       e.CellStyle.BackColor = Color.Beige
    7.     End If
    8.   End If
    9. 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
  •  



Click Here to Expand Forum to Full Width