DataGridView ComboBox Background Color

aman_VB

Member
Joined
Apr 27, 2010
Messages
23
Programming Experience
1-3
Hi all,

I have a DataGridView with ComboBox inside a cell and it seems to work properly. What I want to do is to be able to change the background color of the row based on what the user selects from the drop down ComboBox.
Lets say the ColumnHeaderCell is "Colors" and the ComboBox is a cell and has a list of "Red," "Yellow" and "Green." If you select "Green" the background color of that ROW would be green.

Private Sub DataGridView1_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

If Me.DataGridView1.Columns(e.ColumnIndex).HeaderText = "Colors" Then
e.CellStyle.BackColor = Color.Yellow

The above code only change the background color of single cell, but I want the row.

Thanks and Regards,
 
Look at this code:
VB.NET:
If Me.DataGridView1.Columns(e.ColumnIndex).HeaderText = "Colors" Then
Obviously you're only going to change that column. If you want to change every column then don't filter out every other column. For EVERY cell, you need to get the colour selected for that row and use it. The 'e' parameter can tell you what row you're in so you can get the appropriate column value from that row.
 
Thanks jmc, I found a way to do that. The background color changes based on the selected combo item.
VB.NET:
    Private Sub DataGridView1_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        Try
            With Me.DataGridView1.Rows(e.RowIndex)

                Select Case .Cells(0).Value
                    Case "" 'nothing selected, therefore no color change needed
                        .DefaultCellStyle.BackColor = Nothing
                    Case "Students"
                        .DefaultCellStyle.BackColor = Color.FromArgb(231, 240, 230)
                    Case "Teacher"
                        .DefaultCellStyle.BackColor = Color.FromArgb(254, 253, 218)
                    Case "Classroom"
                        .DefaultCellStyle.BackColor = Color.FromArgb(231, 226, 252)
                    Case "Books"
                        .DefaultCellStyle.BackColor = Color.LightYellow
                End Select
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
 
Back
Top