如果包含无效数据,如何更改DataGridView单元格的BackColor [英] How to change the BackColor of a DataGridView Cell if it contains invalid data

查看:72
本文介绍了如果包含无效数据,如何更改DataGridView单元格的BackColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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







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




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

推荐答案

如果要根据单元格值更改datagridview行的背面颜色,可以使用DatagridviewCellFormating事件。



Ex:

在你的DataGridView1_CellFormatting事件上



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

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


这篇关于如果包含无效数据,如何更改DataGridView单元格的BackColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆