如何在数量低的情况下突出显示特定单元格

时间:2017-02-28 17:35:55

标签: vb.net visual-studio

我正在尝试在VB.NET中开发一个简单的库存系统。我现在已经设置了所有数据库,并且想知道是否有任何代码可以在库存较低时引用该警报用户(例如弹出窗口通知用户库存较低或更改库存数量数据库表变成了不同的颜色。

我尝试过这段代码,但它开始突出显示所有积云。我想突出显示一个名为Quantity的特定单元格,因此当数量低于10时,我希望该数量单元格突出显示为红色。

For i As Integer = 0 To Me.ProductsDataGridView.Rows.Count - 1
    If Me.ProductsDataGridView.Rows(i).Cells(0).Value < 10 Then
       Me.ProductsDataGridView.Rows(i).Cells(0).Style.BackColor =  Color.Red
            MsgBox("Low on stock")
        End If
    Next

我真的很感谢任何建议谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用

DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = Color.Red

但单击列标题

时不会更新

使用

更好
Private Sub DataGridView1_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
    If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then ' should take only 0 and greater than 0 -1 reffers to column header
        If e.ColumnIndex = 0 Then 'column want to compare
            If DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value < 10 Then ' where count is less than ten
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = Color.Red ' if less than 10 change colour here
            End If
        End If
    End If
End Sub

现在无论你做什么,datagridview甚至在刷新后和更新时都会保留其颜色。

答案 1 :(得分:0)

您不需要先使用整数进行迭代。

您可以这样设置:

   For Each row As DataGridViewRow In ProductsDataGridView.Rows
            If row.Cells("yourcolumnname").Value < 10 Then
                row.Cells("yourcolumnname").Style.BackColor = Color.Red
            End If
   Next

如果它小于您想要的数量,这将遍历每一行并相应地突出显示该单元格。