Я не могу получить контроль Я нашел онлайн, чтобы принять период (.). Мне нужно иметь возможность вводить числовые значения с десятичными знаками. Я хотел использовать элемент numericupdown в ячейке datagridview, поэтому я могу использовать стрелки вверх для настройки значений.Пользовательский стол datagridview Control не принимает период (.)
Этот элемент управления управляет элементом управления NumericUpDown в качестве элемента управления редактирования в столбце datagridview. Я нашел его в сети (не помню, где), а ti был основан на аналогичном настраиваемом столбце datagridview, основанном на элементе управления календарем.
Я сделал несколько модификаций, поэтому я мог установить максимальные, минимальные, десятичные места и свойства imcrement.
Однако, даже если десятичные числа установлены равными 2, а приращение равно .1, когда я набираю значение, элемент управления не будет принимать период.
Ниже приведен код, который включает в себя классы для управления столбцом, ячейкой и редактированием. Пожалуйста помоги. Я не знаю, в чем проблема.
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 CalendarCell") End If MyBase.CellTemplate = value End Set End Property Private _Maximum As Decimal = 100 Private _Minimum As Decimal = 0 Private _Increment As Decimal = 0.1 Private _DecimalPlaces As Integer = 2 Public Property DecimalPlaces() As Integer Get Return _DecimalPlaces End Get Set(ByVal value As Integer) If _DecimalPlaces = value Then Return End If _DecimalPlaces = value End Set End Property Public Property Maximum() As Decimal Get Return _Maximum End Get Set(ByVal value As Decimal) _Maximum = value End Set End Property _ Public Property Minimum() As Decimal Get Return _Minimum End Get Set(ByVal value As Decimal) _Minimum = value End Set End Property _ Public Property Increment() As Decimal Get Return _Increment End Get Set(ByVal value As Decimal) _Increment = value End Set End Property End Class
Public Class NumericUpDownCell Inherits DataGridViewTextBoxCell Public Sub New() ' Use the short date format. Me.Style.Format = "N2" End Sub Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _ ByVal initialFormattedValue As Object, _ ByVal dataGridViewCellStyle As DataGridViewCellStyle) ' Set the value of the editing control to the current cell value. MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _ dataGridViewCellStyle) Dim ctl As NumericUpDownEditingControl = _ CType(DataGridView.EditingControl, NumericUpDownEditingControl) RemoveHandler ctl.Enter, AddressOf Me.OnNumericEnter AddHandler ctl.Enter, AddressOf Me.OnNumericEnter ctl.Maximum = CType(Me.DataGridView.Columns(Me.ColumnIndex), NumericUpDownColumn).Maximum ctl.Minimum = CType(Me.DataGridView.Columns(Me.ColumnIndex), NumericUpDownColumn).Minimum ctl.Increment = CType(Me.DataGridView.Columns(Me.ColumnIndex), NumericUpDownColumn).Increment ctl.DecimalPlaces = CType(Me.DataGridView.Columns(Me.ColumnIndex), NumericUpDownColumn).DecimalPlaces ctl.ThousandsSeparator = True ctl.Value = CType(Me.Value, Decimal) End Sub ''' ''' Handle on enter event of numeric ''' ''' ''' ''' Private Sub OnNumericEnter(ByVal sender As Object, ByVal e As EventArgs) Dim control As NumericUpDownEditingControl = CType(sender, NumericUpDownEditingControl) Dim strValue As String = control.Value.ToString("N2") control.Select(0, strValue.Length) End Sub Public Overrides ReadOnly Property EditType() As Type Get ' Return the type of the editing contol that CalendarCell uses. Return GetType(NumericUpDownEditingControl) End Get End Property Public Overrides ReadOnly Property ValueType() As Type Get ' Return the type of the value that CalendarCell contains. Return GetType(Decimal) End Get End Property Public Overrides ReadOnly Property DefaultNewRowValue() As Object Get ' Use the current date and time as the default value. Return 0 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() End Sub Public Property EditingControlFormattedValue() As Object _ Implements IDataGridViewEditingControl.EditingControlFormattedValue Get Return Me.Value.ToString("N2") End Get Set(ByVal value As Object) If TypeOf value Is Decimal Then Me.Value = Decimal.Parse(value) End If End Set End Property _ Public Function GetEditingControlFormattedValue(ByVal context _ As DataGridViewDataErrorContexts) As Object _ Implements IDataGridViewEditingControl.GetEditingControlFormattedValue Return Me.Value.ToString("N2") 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 Case Keys.Up, Keys.Down 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) ' Notify the DataGridView that the contents of the cell have changed. valueIsChanged = True Me.EditingControlDataGridView.NotifyCurrentCellDirty(True) MyBase.OnValueChanged(eventargs) End Sub End Class
Это то, как работает NumericUpDown. 'даже если десятичные числа установлены равными 2, а приращение равно .1' * особенно *, когда разрешены десятичные разряды, пользователь может вводить десятичное значение при использовании KB, а не стрелок. Вероятно, ошибкой является hardcode 'Value.ToString (« N2 »)', который будет игнорировать любое значение, заданное пользователем в стиле ячейки, и если оно * не равно десятичному значению, то отображение на выходе может сбивать с толку – Plutonix
Это делается 2 места. На что вы ссылаетесь? Дело в том, что когда я набрал период, он не будет отображаться в элементе управления редактированием. Казалось, я ничего не набирал. Я попытаюсь удалить оба события этого «ToString (« N2 »)». Период пока не отображается, когда я печатаю его. – Marshall
Я не могу воспроизвести это - он позволяет мне ввести десятичное число. Но он также не сохраняет изменения в настройке. Если я изменю десятичные или минимальные значения, максимальная величина будет использоваться только по умолчанию. Вы забыли сериализовать их – Plutonix