我使用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
但是,我的照片留了下来。谁知道我错过了什么?
答案 0 :(得分:2)
您正在使用一些未绑定的DataGridViewImageColumn
并且如文档中所述,Image
属性指定当列不受数据限制时在没有值的单元格中显示的图像。
因此,通过将单元格值设置为null,您将强制单元格显示Image
属性。
解决问题:
column.DefaultCellStyle.NullValue = Nothing
Image
属性。 Value
属性。您可以在循环中手动设置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