HELP ME plzzz!
I try to make my datagridview rows change colour depending on value on a row cell. I ve tryed everything i found on the web but nothing.. plz help
Last I tryed this one: but stil nothing :(

Recommended Answers

All 3 Replies

I would do the changes on the CellValueChanged event.

For this example, I have assumed that there is a datagridview column named "Column3" and that you are testing against an integer value. Make changes to column name and field type as necessary to match your data.

Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
      'exit if not the target column
      If DataGridView1.Columns(e.ColumnIndex).Name <> "Column3" Then Exit Sub
      'since we know the column is the correct one, can use e.ColumnIndex
      'to reference the cell of interest
      Dim testvalue As Int32
         'make sure the value can be converted to the proper type
         testvalue = CType(DataGridView1(e.ColumnIndex, e.RowIndex).Value, Int32)
         If testvalue = 3 Then
            DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.AliceBlue
            If DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor <> DataGridView1.RowsDefaultCellStyle.BackColor Then
               'set to the default
               DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = DataGridView1.RowsDefaultCellStyle.BackColor
            End If
         End If
      Catch ex As Exception
         'no big deal for this example, not as I am not validating input
         Exit Sub
      End Try
   End Sub

You can modify the individual cells in a datagridview via the Style property as follows:

DataGridView1.Rows(1).Cells(1).Style.BackColor = Color.Aqua

Hope this helps u....

'Open Connection
Dim myCommand As SqlCommand
myCommand = New SqlCommand("SELECT ProdName from HMS.dbo.Product where Inventory < ReorderLimit", Connection)
Dim reader As SqlDataReader = myCommand.ExecuteReader
While reader.Read()
      For RCnt As Integer = 0 To dgvInventory.Rows.Count - 1
          If dgvInventory.Rows(RCnt).Cells("Product").Value = reader("ProdName") Then
             dgvInventory.Rows(RCnt).DefaultCellStyle.BackColor = Color.MediumPurple
             dgvInventory.Rows(RCnt).DefaultCellStyle.ForeColor = Color.White
          End If
End While
'Close Connection
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.