Vb.net Question

Datagridview not changing image in cell

I am working with DataGridViewObject in my Windows form, using VB.NET. I have three columns that need to display icons. But, based on some info from row, that icons will be shown or not. My problem is that image won't change when I change its value. Basically, I define my columns like this:

Dim column1 As DataGridViewImageColumn = New DataGridViewImageColumn()
column1.Image = My.Resources.image1
column1.Width = 30
dw.Columns.Add(column1)

Dim column2 As DataGridViewImageColumn = New DataGridViewImageColumn()
column2.Image = My.Resources.image2
column2.Width = 30
dw.Columns.Add(column2)

Dim column3 As DataGridViewImageColumn = New DataGridViewImageColumn()
column3.Image = My.Resources.image3
column3.Width = 30
dw.Columns.Add(column3)


After the data is filled, I am looping through rows, and if I do not want to show the images in that row, I do:

Dim cell1 As DataGridViewImageCell = row.Cells(9)
Dim cell2 As DataGridViewImageCell = row.Cells(10)
Dim cell3 As DataGridViewImageCell = row.Cells(11)

cell1.Value = Nothing
cell2.Value = Nothing
cell3.Value = Nothing


But, my images stay. Anyone knows what am I missing?

Answer

You are using some unbound DataGridViewImageColumn and as mentioned in documents, The Image property specifies an image that is displayed in cells with no values when the column is not data-bound.

So by setting a cell value to null, you are forcing the cell to show the Image property.

To solve the problem:

  1. For your columns set column.DefaultCellStyle.NullValue = Nothing
  2. Don't set the Image property.
  3. Each time you want to show the image, assign the image to Value property of cell.

You can set value of Cell manually in a loop or using CellFormatting event. For example:

Private Sub DataGridView1_CellFormatting(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting

    If (e.RowIndex >= 0 AndAlso e.ColumnIndex = 2) Then 
        If (e.RowIndex Mod 2 = 0) Then 'Use any criteria which you need, it's a test
            e.Value = My.Resources.Image1
        Else
            e.Value = DBNull.Value
            e.CellStyle.NullValue = Nothing
        End If
    End If

   ' Do the same for other image columns. 

End Sub
Comments