正如标题所说。
我从SQL Compact DB中收集了一堆值,并将它们放入DataGridView中。一个单元格(在本例中为“Status”)包含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?我当然可以在每次对列表进行排序时进行循环,但它感觉不对吗?
答案 0 :(得分: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