vb.netwinformsdatagridviewdatagridviewcolumndatagridviewimagecolumn

How to change or remove the null image in a DataGridViewImageColumn including the new Row


How to remove null image in datagridview column image in vb.net?

Is there a way to remove null image in datagridview column image?

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
        item.Add(New item With {
            .CodeProduct = TextBox1.Text
        })
        Grid.Bind(item)
        TextBox1.Clear()
    End If
End Sub

Public Class item
    Public Property No() As Integer
    Public Property CodeProduct() As String
    Public Function GetAvatar() As DataGridViewAvatar
        Return New DataGridViewAvatar() With {
            .Value = CType(Me.CodeProduct, String),
            .Icon = Image.FromFile("money.png")
        }
    End Function

remove null image in datagridview column image

Before use CustomImageCell

Before use CustomImageCell

after use CustomImageCell

after use CustomImageCell


Solution

  • To replace the default ImageInError object (Icon or Bitmap, depending on the .NET version) that is presented when a DatGridViewImageCell has no value or as the placeholder in the New Row object, you can use a custom DatGridViewImageCell that sets the DefaultNewRowValue and Style.NullValue properties in its Constructor.

    Then replace the CellTemplate of a DataGridViewImageColumn with this one.
    Done like this, you set the value just once and it's used everywhere. No need to handle events and, possibly, leak graphic resources in the meanwhile.

    Sample class:

    Friend Class CustomImageCell
        Inherits DataGridViewImageCell
        Public Sub New()
            Me.New(Nothing)
        End Sub
        Public Sub New(ByVal defaultImage As Object)
            MyBase.New(False)
            DefaultNewRowValue = defaultImage
            Style.NullValue = defaultImage
        End Sub
    
        ' Handle as needed, if necessary
        Public Overrides ReadOnly Property DefaultNewRowValue As Object
    End Class
    

    To replace the default Cell with this one and set a null value (default), for example:

    For Each col In [Some DataGridView].Columns.OfType(Of DataGridViewImageColumn)()
        col.CellTemplate = New CustomImageCell()
    Next
    

    Or specify a different object in the Constructor You could also build a custom DataGridViewImageColumn that uses this Cell as CellTemplate. It would also appear in the Designer of the DataGridView when new Columns are added to the grid using the standard tool