0

正如标题所说。

我从 SQL Compact DB 中收集了一堆值,并将它们放入 DataGridView。一个单元格(在本例中为“状态”)包含一个 varchar 字段。我想根据它的值设置这个字段的背景颜色。例如,如果这个值是 == "5" 或 "V",我希望它是红色的,如果它是 "4" 或 "B",我希望它是绿色的或类似的东西。

我尝试使用一个循环来检查此单元格中的每个值并设置背景颜色,但是当我单击 DataGridView 标题以更改值的顺序时,颜色会消失。并且......由于有很多数据,因此通过循环这些值来实现这个结果是不正确的。

我用这样的东西收集值:

Dim Source as Bindingsource = GetBinding()
Form1.ClientsDataGrid.Columns("CustomerNr").DataPropertyName = "CustNR"
Form1.ClientsDataGrid.Columns("CustomerName").DataPropertyName = "Name"
Form1.ClientsDataGrid.Columns("Status").DataPropertyName = "Status"
Form1.ClientsDataGrid.DataSource = Source

'Just in case, this is how i set the colors now
For Each TblRow As DataGridViewRow In Form1.ClientsDataGrid.Rows
   If TblRow.Cells(3).Value.ToString = "5" Or TblRow.Cells(3).Value.ToString = "V" Then
       TblRow.Cells(3).Style.BackColor = Color.Red
   ElseIf (TblRow.Cells(3).Value.ToString = "4" Or TblRow.Cells(3).Value.ToString = "B" Then
        TblRow.Cells(3).Style.BackColor = Color.Green
    End If
Next

GetBinding() 看起来像这样:

'blah blah make connections
Dim Com As New SqlCeCommand("SELECT Customernumber AS CustNR, Customername AS Name, Customerstatus AS Status FROM Mytable", Con)
Dim dataAdapter As SqlCeDataAdapter
dataAdapter = New SqlCeDataAdapter(Com)
Dim dataSet As New DataSet
dataAdapter.Fill(dataSet, "Mytable")
Dim bind As BindingSource
bind = New BindingSource(dataSet, "Mytable")
Con.Close()
Com = Nothing
Return bind

有没有办法将这些规则直接设置到 DataGridView?我当然可以在每次对列表进行排序时进行循环,但感觉不对?

4

1 回答 1

1

在 rowprepaint 事件中执行此操作 .. 应用于行 ..

Private Sub ClientsDataGrid_RowPrePaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles ClientsDataGrid.RowPrePaint

    Dim tblRow as DataGridViewRow = ClientsDataGrid.Rows(e.RowIndex)

    If (TblRow.Cells(3).Value.ToString = "5" Or TblRow.Cells(3).Value.ToString = "V" Then

        tblRow.DefaultCellStyle.BackColor = Color.Red

    ElseIf (TblRow.Cells(3).Value.ToString = "4" Or TblRow.Cells(3).Value.ToString = "B" Then

        tblRow.DefaultCellStyle.BackColor = Color.Green

    End If

End Sub
于 2013-06-04T15:07:57.750 回答