Datagridview不会更改单元格中的图像

时间:2016-10-17 14:49:55

标签: vb.net winforms datagridview datagridviewimagecolumn

我使用VB.NET在Windows窗体中使用DataGridViewObject。我有三列需要显示图标。但是,根据行中的某些信息,将显示或不显示图标。我的问题是,当我改变它的价值时,图像不会改变。基本上,我像这样定义我的列:

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)

数据填满后,我循环遍历行,如果我不想在该行中显示图像,我会这样做:

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

但是,我的照片留了下来。谁知道我错过了什么?

1 个答案:

答案 0 :(得分:2)

您正在使用一些未绑定的DataGridViewImageColumn并且如文档中所述,Image属性指定当列不受数据限制时在没有值的单元格中显示的图像。

因此,通过将单元格值设置为null,您将强制单元格显示Image属性。

解决问题:

  1. 为您的列设置column.DefaultCellStyle.NullValue = Nothing
  2. 不要设置Image属性。
  3. 每次要显示图像时,请将图像指定给单元格的Value属性。
  4. 您可以在循环中手动设置Cell的值,也可以使用CellFormatting事件。例如:

    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
    
相关问题