Domanda

As the title says.

I collect a bunch of values from a SQL Compact DB, and puts them into a DataGridView. One cell ("Status" in this case) contains a varchar field. I want to set the background color of this field depending on its value. For example, if this value is == "5" or "V", i want it to be red, if it's "4" or "B" i want it green or something like that.

I've tried with a loop that checks every value in this cell and sets the background color, but when i click in the DataGridView headers to change the order of the values the colors disapears. And... It does not feel right to achieve this result by looping the values afterwards since there's quite much data.

I collect the values with something like this:

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

and the GetBinding() looks something like this:

'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

Is there a way to set these rules directly to the DataGridView? I can of course do the looping every time i sort the list, but it does'nt feel right?

È stato utile?

Soluzione

Do that in rowprepaint event .. apply to the row ..

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top