Reputation: 171
I have a DataGridView like this:
I am binding the DataGridView like this:
Dim cmd As New SqlCommand("DashBordFetch", con.connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@locid", SqlDbType.Int).Value = locid
da.SelectCommand = cmd
da.Fill(ds)
DGVDashBoard.DataSource = ds.Tables(0)
I want to my DataGridView to have a red row color when the Value is 1. How can I do that? I am working in VB.NET.
I have tried the code in one of the answers provided, it looks like this:
Upvotes: 3
Views: 26619
Reputation: 755
here's my code:
For Each row As GridViewRow In GridView1.Rows
row.BackColor = Drawing.Color.White
Next row
Upvotes: 0
Reputation: 11
'Use this code for change color of specific row in cellformatting event of 'datagridview
For Each drview As DataGridViewRow In dgrawPRoducts.Rows
If drview.Cells.Count >= 14 Then
If Not IsNothing(drview.Cells(14).Value) Then
If drview.Cells(14).Value.ToString.Trim = "N" Then
For i As Integer = 0 To drview.Cells.Count - 1
drview.Cells(i).Style.ForeColor = Color.Red
drview.Cells(i).Style.BackColor= Color.Gray
Next
End If
End If
End If
Next
Upvotes: 1
Reputation: 11
Thanks Senthilkumar I was looking for something that would allow me to color the background of a row if the Text equals Closed. Here is my final solution I just had to add the ToString after value. The DataGridviewTextBoxColumn16 name is from the datagridview properties. Click the Arrow at the top right of DataGridView, edit columns and find the name value. Hope that helps someone.
For Each rw As DataGridViewRow In DataGridView1.Rows
If rw.Cells("DataGridViewTextBoxColumn16").Value.ToString = "Closed" Then
rw.DefaultCellStyle.BackColor = Color.Red
Else
rw.DefaultCellStyle.BackColor = Color.Green
End If
Next
Upvotes: 1
Reputation: 14470
Sub CustomersGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If(your condition)
e.Row.BackColor = Drawing.Color.Red
End If
End If
End Sub
Upvotes: 2
Reputation: 2578
For Each rw As DataGridViewRow In DataGridView1.Rows
If rw.Cells("slno").Value =1 Then
rw.DefaultCellStyle.BackColor = Color.Red
Else
rw.DefaultCellStyle.BackColor = Color.Green
End If
Next
Upvotes: 0
Reputation: 1295
Try this
Private Sub DGVDashBoard_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGVDashBoard.CellFormatting
Dim drv As DataRowView
If e.RowIndex >= 0 Then
' Add Your condition here ignore following
If e.RowIndex <= ds.Tables(0).Rows.Count - 1 Then
drv = ds.Tables(0).DefaultView.Item(e.RowIndex)
Dim c As Color
If drv.Item("Value").ToString = "1" Then
c = Color.Red
End If
e.CellStyle.BackColor = c
End If
End If
End Sub
Let me know if this doesn't work.
Upvotes: 4