Change the color of a row in datagrid when certain column is not blank
I have the following code that 's giving me the following error when I run it. I attached a screen print of the errror.
As you can see in the screen print it says: Column Named Vacation_On cannot be found.
Which doesn't make sense, because the column exists in my Access database and I can see it in the datagridview.
Any ideas what's causing the error??
thanks
For Each row As DataGridViewRow In Me.DataGridView1.Rows If row.Cells("Vacation_On").Value Is DBNull.Value Then row.DefaultCellStyle.BackColor = Color.White Else row.DefaultCellStyle.BackColor = Color.Aqua End If Next
Try like this. On the row.Cells(1).Value change the 1 for the number of the column that represents Vacation_On and the code should work.
jppinto
For Each row As DataGridViewRow In Me.DataGridView1.Rows If row.Cells(1).Value Is DBNull.Value Then row.DefaultCellStyle.BackColor = Color.White Else row.DefaultCellStyle.BackColor = Color.Aqua End IfNext
It's not working, more rows are changing colors than are supposed to.
jppinto
But at least you don't get the error anymore, right?
Did you putted the correct index of the column you want to check is the cell value is blank? In my example I assumed that Vacation_On is the the second column (index 1). The code is correct, maybe the column that you're checking is not the correct one...
This should color the rows where the column Vacation_on is null in white (index 8) and color the rows where Vacation_On is filled in Aqua. Is that what you want to do? You have to make sure that, when there is no date in Vacation_On field on your database, that the field is null or empty and doesn't have like a 0 on it.
I've tryed the code on and this is the result that I got (please see attached picture). To get this result I've used this code:
For Each row As DataGridViewRow In Me.grdRelatorio.Rows
If Not row.IsNewRow Then
If row.Cells(4).Value Is DBNull.Value Then
row.DefaultCellStyle.BackColor = Color.White
Else
row.DefaultCellStyle.BackColor = Color.Aqua
End If
End If
Next
When the 4th column is empty, the field on the database is empty!
jppinto
For Each row As DataGridViewRow In Me.grdRelatorio.Rows If Not row.IsNewRow Then If row.Cells(8).Value Is DBNull.Value Then row.DefaultCellStyle.BackColor = Color.White Else row.DefaultCellStyle.BackColor = Color.Aqua End If End IfNext
No luck, the Vacation_On column is empty in the whole database. I should have one color, but I don't.
jppinto
I'm getting out of options here...
Can you post an sample of your data on your table, the definition of your table and a screen shot of the datagridview with data after running my last code to see how it looks?
I've answered another question sometime ago about this and I was able to solve the problem. Take a look at this to see if you can see anything more that can help you because I can't figure it out what the problem is:
jppinto
Open in new window