I need to change the color of a row in datagridview but my code is not working for me. I always get a error that says "Column named Quantity: cannot be found. Parameter name: columnName"
Here is my code:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("Quantity:").Value < 5 Then
Me.DataGridView1.Rows(i).Cells("Quantity:").Style.ForeColor = Color.Red
End If
Next
End Sub
Please help me fix it. Thank you.
This might be helpful
I converted this from C# ('From: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=74)
Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)
Handles dgv_EmployeeTraining.RowPostPaint
If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)
'<== This is the header Name
'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then
'<== But this is the name assigned to it in the properties of the control
If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then
dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)
Else
dgvRow.DefaultCellStyle.BackColor = Color.LightPink
End If
End If
End Sub
I fixed my error. just removed "Value" from this line:
If drv.Item("Quantity").Value < 5 Then
So it will look like
If drv.Item("Quantity") < 5 Then
Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
Dim drv As DataRowView
If e.RowIndex >= 0 Then
If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
Dim c As Color
If drv.Item("Quantity").Value < 5 Then
c = Color.LightBlue
Else
c = Color.Pink
End If
e.CellStyle.BackColor = c
End If
End If
End Sub
Just remove the :
in your Quantity
. Make sure that your attribute is the same with the parameter you include in the code, like this:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
End If
Next
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With