Set the BackColor of a Row In a Datagrid With Value Condition

From HashVB
Jump to: navigation, search

I made this code for set the .backcolor in a entire row on a datagridview control, looking for a value that's condition for the color. This is usefull if u have a datagridview control that u can sort with the headers buttons and u need the color again.

This is for VB.NET Any suggestion please email me: msn at sistemas com ar

I hope this can be useful, anyway u can askme at #vb on Undernet, nickname Nocturno or Fuego


For this example u need a table and a datagridview control.


Firs of all, we set some datagridview1 properties.


      With DataGridView1
           .AllowUserToAddRows = False
           .AllowUserToDeleteRows = False
           .AllowUserToOrderColumns = True
           .AllowUserToResizeRows = False
           .ReadOnly = True
           .SelectionMode = DataGridViewSelectionMode.FullRowSelect
           .MultiSelect = False
           .BackgroundColor = Color.White
       End With

We need create a table. For this example i create it with code and one by one, to be more clear. Watch up the datagridview1.datasource


       public mitabla As New DataTable
       Dim Detalle As New DataColumn("Tipo")
       Dim Informacion As New DataColumn("Valor")
       mitabla.Columns.Add(Detalle)
       mitabla.Columns.Add(Informacion)
       mitabla.Rows.Add("")
       mitabla.Rows.Add("")
       mitabla.Rows.Add("")
       mitabla.Rows.Add("")
       mitabla.Rows.Add("")
       mitabla.Rows(0).Item(0) = "ajose"
       mitabla.Rows(1).Item(0) = "bjose"
       mitabla.Rows(2).Item(0) = "cjose"
       mitabla.Rows(3).Item(0) = "zjose"
       mitabla.Rows(4).Item(0) = "ejose"
       mitabla.Rows(0).Item(1) = "1"
       mitabla.Rows(1).Item(1) = "3"
       mitabla.Rows(2).Item(1) = "2"
       mitabla.Rows(3).Item(1) = "6"
       mitabla.Rows(4).Item(1) = "4"
       DataGridView1.DataSource = mitabla


So, the problem is... ¿What event refresh the datagridview also if u dont change the values but u sort it again?

So, in the Paint event of datagridview1 we call the function:


       Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As  
       System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
       colorDG(1, "6", DataGridView1, Color.AliceBlue)
   End Sub


We are painting the row where: item is 1, value of the cell is "6", in the datagridview1, with the color aliceblue. Now, the function:


   Public Sub colorDG(ByVal item As Integer, ByVal valorcampo As Object, ByVal DG As Object, 
   ByVal tinte As Color)
       Dim xa As Integer
       For xa = 0 To DG.Rows.Count - 1
           If DG.Item(item, xa).Value Is valorcampo Then
               DG.Rows(xa).DefaultCellStyle.BackColor = tinte
           End If
       Next
   End Sub