【问题标题】:Setting backgroundcolors in DataGridViewCells depending on the value from SQL (VB.Net winforms)根据 SQL (VB.Net winforms) 中的值在 DataGridViewCells 中设置背景颜色
【发布时间】:2013-06-04 14:57:04
【问题描述】:

正如标题所说。

我从 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?我当然可以在每次对列表进行排序时进行循环,但感觉不对?

【问题讨论】:

    标签: vb.net winforms datagridview background-color datagridviewcolumn


    【解决方案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
    

    【讨论】:

    • 你是什么意思?在那个代码中你忘记了循环,或者我只是想念你的想法?在这种情况下,TblRow 未设置为任何内容。有没有办法说更像 If MyDatagrid.Cells(3) 并在这里检查整个列而不循环?
    猜你喜欢
    • 2011-12-27
    • 2015-07-17
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多