如果包含无效数据,如何更改DataGridView单元格的BackColor

时间:2013-07-24 18:41:13

标签: vb.net validation datagridview background-color

我试图找出是否有办法让我将单个datagridviewcell的背景色更改为红色(如果单元格包含某个值)。例如:

 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

因为它现在代表我的代码将使得datagridview的整个第一列为红色,如果一个或多个单元格包含无效数据。我希望只有具有无效数据的单元格才是红色的。如果有人能想到这一点我会非常感激! :)

1 个答案:

答案 0 :(得分:2)

像这样访问单元格

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