Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to find out if there is a way for me to change the backcolor of an individual datagridviewcell to red if the cell contains a certain value. For example:

VB
If (columnindex = 1) Then

        Dim cellData = DataGridView1.Rows(rowindex).Cells(columnindex).Value
        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
            'Do nothing because this is allowed
            'Now I want to set the default backcolor for the datagridview to white
            DataGridView1.Rows(rowindex).Cells(columnindex).DefaultCellStyle.BackColor = Color.White
        ElseIf cellData < 0 Or cellData > 1 Then
            MessageBox.Show("Value Must be between 0 and 1")
            DataGridView1.Rows(rowindex).Cells(columnindex).Value = 0
            'This is where I'm hoping to make only the cells that values are not between 1 or zero have a backcolor of red
            DataGridView1.Rows(rowindex).Cells(columnindex).DefaultCellStyle.BackColor = Color.Red
            Exit Sub

        End If
    End If



as it currently stands my code will make the entire first column of the datagridview red if one ore more cells contain invalid data. I'm hoping for only the cells with the invalid data to be red. If anyone can figure this out I would greatly appreciate it! :)
Posted
Comments
CHill60 24-Jul-13 15:14pm    
Try DataGridView1.Item(columnindex, rowindex).Style.BackColor = Color.Red
Maciej Los 24-Jul-13 16:09pm    
My virtual 5!
CHill60 24-Jul-13 16:15pm    
Thank you ... didn't post it as a solution as I haven't got any means of testing it at the moment. I thought it was right though and your (virtual) 5 confirms it :-)
CAS1224 24-Jul-13 16:19pm    
For some reason its not working for me. I wonder if I'm doing something else wrong :\
Maciej Los 24-Jul-13 16:31pm    

1 solution

You can use DatagridviewCellFormating Event if you want to change the back color of you datagridview row based on cell value.

Ex:
On your DataGridView1_CellFormatting Event

VB
Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
Dim obj As Object = row.Cells("ColumnName").Value
 If Not IsDBNull(row.Cells("ColumnName").Value) Then
  If row.Cells("ColumnName").Value < 0 Then
     row.DefaultCellStyle.BackColor = Color.Red

  ElseIf row.Cells("ColumnName").Value > 0 Then
     row.DefaultCellStyle.BackColor = Color.White
  End If
 End If

Return
 
Share this answer
 
v3
Comments
CAS1224 25-Jul-13 8:11am    
Thank you so much! I used a combination of your answer and CHIll60's answer. Thanks guys you're awesome!

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900