Link to home
Start Free TrialLog in
Avatar of ranhell
ranhellFlag for Mexico

asked on

Datagridview back color depending on cell value

On the code snipet I'm changing the backcolor of the cell depending on the cell valueon a specific column, it works, but the problem is that it takes the backcolor of the last cell value found.
I mean, If the cell value "ACTIVO" is found the back color changes to green, and the if the cell value "DUPLICADO" is found the back color changes to red on every cell eventhoug it was green
So I want to mantain 2 different backcell color depending on the cell value withing the same column, is this psosible.??




Private Sub DataGridView1_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
       
        For Each dr As DataGridViewRow In DataGridView1.Rows
            Select Case dr.Cells("ESTATUS").Value
                Case "ACTIVO"
                    'DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.GreenYellow
                    'DataGridView1.RowsDefaultCellStyle.BackColor = Color.GreenYellow
                    DataGridView1.Columns("ESTATUS").DefaultCellStyle.BackColor = Color.GreenYellow
 
                Case "DUPLICADO"
                    DataGridView1.Columns("ESTATUS").DefaultCellStyle.BackColor = Color.Red
                    'DataGridView1.RowsDefaultCellStyle.BackColor = Color.Red
 
            End Select
        Next
        
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Toms Edison
Toms Edison
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ranhell

ASKER

Excellent, thanks.

Now I don't mean to be abusive here but can I ask
How would I do this without using the event:
Private Sub DataGridView1_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete

What I mean is if I wanted to do the same but with my on created event or Function, how would I declare it..??

I will accept your anwser as the solution is mostly a follow up question

The best place to do it is in RowDataBound  event handler where each row gets added to datagrid one by one.
If you want to do this in your own event handler you can declare as below

Private Sub UpdateStatus(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete

this will get called when DataBindingComplete event occurs

You can also write a seperate function to do the same task and call it from within DataGridView1_DataBindingComplete function



Avatar of ranhell

ASKER

Thanks