vb.netdatagridviewcolumnnumericupdown

Display the default value in the newly added row (DataGridView)


There is a custom NumericUpDownColumn:

Module NumUpDownModule
    Public defRowValue As String = "0"
End Module
Public Class NumericUpDownColumn
    Inherits DataGridViewColumn
    Public Sub New()
        MyBase.New(New NumericUpDownCell())
    End Sub

    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)
            ' Ensure that the cell used for the template is a CalendarCell.
            If Not (value Is Nothing) AndAlso Not value.GetType().IsAssignableFrom(GetType(NumericUpDownCell)) Then
                Throw New InvalidCastException("Must be a NumericUpDownCell")
            End If
            MyBase.CellTemplate = value
        End Set
    End Property
End Class

Public Class NumericUpDownCell
    Inherits DataGridViewTextBoxCell
    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle)
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)
        Dim ctl As NumericUpDownEditingControl = CType(DataGridView.EditingControl, NumericUpDownEditingControl)
        If Me.Value Is Nothing Or DBNull.Value.Equals(Me.Value) Then
            ctl.Value = defRowValue
        Else
            ctl.Value = CType(Me.Value, Decimal)
        End If
    End Sub

    Public Overrides ReadOnly Property EditType() As Type
        Get
            Return GetType(NumericUpDownEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            Return GetType(Decimal)
        End Get
    End Property

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            Return defRowValue
        End Get
    End Property
End Class

Class NumericUpDownEditingControl
    Inherits NumericUpDown
    Implements IDataGridViewEditingControl
    Private dataGridViewControl As DataGridView
    Private valueIsChanged As Boolean = False
    Private rowIndexNum As Integer

    Public Sub New()
        Me.DecimalPlaces = 0
    End Sub

    Public Property EditingControlFormattedValue() As Object Implements IDataGridViewEditingControl.EditingControlFormattedValue
        Get
            Return Me.Value.ToString()
        End Get
        Set(ByVal value As Object)
            Me.Value = Decimal.Parse(value.ToString())
        End Set
    End Property

    Public Function GetEditingControlFormattedValue(ByVal context As DataGridViewDataErrorContexts) As Object Implements IDataGridViewEditingControl.GetEditingControlFormattedValue
        If DBNull.Value.Equals(Me.Value) Then
            Return defRowValue
        Else
            Return Me.Value.ToString()
        End If
    End Function

    Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As DataGridViewCellStyle) Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl
        Me.Font = dataGridViewCellStyle.Font
        Me.ForeColor = dataGridViewCellStyle.ForeColor
        Me.BackColor = dataGridViewCellStyle.BackColor
    End Sub

    Public Property EditingControlRowIndex() As Integer Implements IDataGridViewEditingControl.EditingControlRowIndex
        Get
            Return rowIndexNum
        End Get
        Set(ByVal value As Integer)
            rowIndexNum = value
        End Set
    End Property

    Public Function EditingControlWantsInputKey(ByVal key As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean Implements IDataGridViewEditingControl.EditingControlWantsInputKey
        ' Let the DateTimePicker handle the keys listed.
        Select Case key And Keys.KeyCode
            Case Keys.Left, Keys.Up, Keys.Down, Keys.Right, Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp
                Return True
            Case Else
                Return False
        End Select
    End Function

    Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) Implements IDataGridViewEditingControl.PrepareEditingControlForEdit
        ' No preparation needs to be done.
    End Sub

    Public ReadOnly Property RepositionEditingControlOnValueChange() As Boolean Implements IDataGridViewEditingControl.RepositionEditingControlOnValueChange
        Get
            Return False
        End Get
    End Property

    Public Property EditingControlDataGridView() As DataGridView Implements IDataGridViewEditingControl.EditingControlDataGridView
        Get
            Return dataGridViewControl
        End Get
        Set(ByVal value As DataGridView)
            dataGridViewControl = value
        End Set
    End Property

    Public Property EditingControlValueChanged() As Boolean Implements IDataGridViewEditingControl.EditingControlValueChanged
        Get
            Return valueIsChanged
        End Get
        Set(ByVal value As Boolean)
            valueIsChanged = value
        End Set
    End Property

    Public ReadOnly Property EditingControlCursor() As Cursor Implements IDataGridViewEditingControl.EditingPanelCursor
        Get
            Return MyBase.Cursor
        End Get
    End Property

    Protected Overrides Sub OnValueChanged(ByVal eventargs As EventArgs)
        valueIsChanged = True
        Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
        MyBase.OnValueChanged(eventargs)
    End Sub
End Class

DataGridView AllowUserToAddRows property set to FALSE.

When adding a new row, the default value in the NumericUpDownCell is not displayed.

How to display the default value when adding a new line?

If the AllowUserToAddRows property is changed to TRUE, everything is displayed correctly. However it must always be false.


Solution

  • It depends on how you populate the grid. If you bind it to a DataTable or BindingSource that is bound to a DataTable, then you need to set the DataColumn.DefaultValue property.

    For example:

    Dim dt = New DataTable()
    dt.Columns.AddRange({
        New DataColumn("TextColumn", GetType(String)),
        New DataColumn("DecimalColumn", GetType(Decimal)) With {.DefaultValue = 0D}
    })
    
    DataGridView1.AutoGenerateColumns = False
    DataGridView1.DataSource = New BindingSource(dt, Nothing)
    DataGridView1.Columns.AddRange(
        {
        New DataGridViewTextBoxColumn With {
        .Name = "TextColumn",
        .DataPropertyName = .Name,
        .HeaderText = "Some Text"
        },
        New NumericUpDownColumn With {
        .Name = "DecimalColumn",
        .DataPropertyName = .Name,
        .HeaderText = "Value",
        .SortMode = DataGridViewColumnSortMode.Automatic
        }})
    

    On the other hand, if you have an unbound grid and use the Rows collection, then you need to override the DataGridViewCell.GetValue method to return a default Decimal value instead of the default Nothing value. Either return the Value property if the boxed type is Decimal, or convert the value of the DataGridViewCell.DefaultNewRowValue property to decimal.

    Public Class NumericUpDownCell
        Inherits DataGridViewTextBoxCell
    
        Public Overrides Sub InitializeEditingControl(
                                rowIndex As Integer,
                                initialFormattedValue As Object,
                                dataGridViewCellStyle As DataGridViewCellStyle)
            MyBase.InitializeEditingControl(
                rowIndex,
                initialFormattedValue,
                dataGridViewCellStyle)
    
            Dim ctl As NumericUpDownEditingControl = DirectCast(
                DataGridView.EditingControl,
                NumericUpDownEditingControl)
            ctl.Value = GetValueOrDefault(Value)
        End Sub
    
        Public Overrides ReadOnly Property EditType() As Type
            Get
                Return GetType(NumericUpDownEditingControl)
            End Get
        End Property
    
        Public Overrides ReadOnly Property ValueType() As Type
            Get
                Return GetType(Decimal)
            End Get
        End Property
    
        Public Overrides ReadOnly Property DefaultNewRowValue() As Object
            Get
                Return 0D
            End Get
        End Property
    
        Protected Overrides Function GetValue(rowIndex As Integer) As Object
            Return GetValueOrDefault(MyBase.GetValue(rowIndex))
        End Function
    
        Private Function GetValueOrDefault(val As Object) As Decimal
            Dim outVal As Decimal
    
            If val IsNot Nothing AndAlso
                val IsNot DBNull.Value AndAlso
                Decimal.TryParse(val.ToString(), outVal) Then
                Return outVal
            Else
                Return Convert.ToDecimal(DefaultNewRowValue)
            End If
        End Function
    End Class