I have a few datagridview's, listing different bits and bobs from a mysql database.
One of them has a column called 'outcome'.
This can be either 'Yes', 'Pending' or 'No'.
I need to format this list based on that value.
I'm using the following at the moment...
Private Sub nb_myleads_dgv_CellFormattin(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles nb_myleads_dgv.CellFormatting
If e.ColumnIndex = nb_myleads_dgv.Columns("outcome").Index Then
If e.Value.ToString = "Yes" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkGreen
ElseIf e.Value.ToString = "Pending" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkOrange
ElseIf e.Value.ToString = "No" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkRed
End If
End sub
End If
It seem that I have to have my column 'outcome' visible in the DGV for this to work. I have gotten around this by setting this column width to 3 pixels, but that seems a little dirty. Is it not possible to format cells in a datagridview based on the value of a hidden column?
Thanks in advance
I believe your problem is that cell has to be visible, otherwise it will never pass if statement.
The CellFormatting event occurs every time each cell is painted , so you should avoid lengthy processing when handling this event. This event also occurs when the cell FormattedValue is retrieved or its GetFormattedValue method is called.
I would get rid off this if statement and do something like this:
Dim str as string = dataGridView1.Rows[e.RowIndex].Cells["outcome"].Value.ToString
If str = "Yes" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkGreen
ElseIf str = "Pending" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkOrange
ElseIf str = "No" Then
nb_myleads_dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.DarkRed
End If
Why not just loop through the rows with a for each and colorize based on the cell value. It won't matter if it's visible or not.
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
Select Case row.Cells(2).Value.ToString
Case "Yes"
row.DefaultCellStyle.BackColor = Color.DarkGreen
Case "Pending"
row.DefaultCellStyle.BackColor = Color.DarkOrange
Case "No"
row.DefaultCellStyle.BackColor = Color.DarkRed
End Select
End If
Next
Where in this case, column 3 (cells(2) is hidden. You would do this after populating the grid instead of in the cellformatting
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.