0
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:

 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! :)

1

1 Answers

2
votes

Access the cell like this instead

DataGridView1.Item(columnindex, rowindex).Style.BackColor = Color