DataGridView Cell Editing issue with decimal/hexadecimal formatting

回眸只為那壹抹淺笑 提交于 2019-12-11 02:23:56

问题


I have a DataGridView bound to a DataTable that has 1+16 columns defined as Integer.

The default cell style is hexadecimal 2 digits (.Format="X2").

When entering in cell editing I would like to provide to the user, the possibility to write the value in decimal or hexdacimal.

  1. Hexadecimal could be written like, for example, 0x00, 0X01, x02, XFF
  2. Decimal like 0, 1, 2, 15

For this reason in EditingControlShowing I add "0x" to the TextBox value

Private Sub BankGrid_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)

    Dim grid As DataGridView = DirectCast(sender, DataGridView)
    If Not TypeOf e.Control Is TextBox Then Return

    Dim tb As TextBox = DirectCast(e.Control, TextBox)
    tb.Text = "0x" & tb.Text

    RemoveHandler tb.KeyPress, AddressOf TextBox_KeyPress
    AddHandler tb.KeyPress, AddressOf TextBox_KeyPress

End Sub

while in TextBox_KeyPress sub I perform all input filtering to avoid invalid inputs.

What I cannot understand is to which event may I attach to detect when the editing is finished. I would like something opposite to EditingControlShowing so that I can remove "0x" but I didn't found it.


回答1:


After try all possible events both in TextBox and in DataGRidView I finally found one useful for my case.

CellParsing

I copy my code maybe it could help someone else :)

   Private Sub BankGrid_CellParsing(ByVal sender As Object, ByVal e As DataGridViewCellParsingEventArgs)

        Dim grid As DataGridView = DirectCast(sender, DataGridView)
        Dim cell As CustomCell = DirectCast(grid(e.ColumnIndex, e.RowIndex), CustomCell)

        If e.Value Is Nothing OrElse String.IsNullOrEmpty(e.Value.ToString) Then
            e.Value = cell.Value
        Else

            Dim iValue As Integer
            If TryParseNumeric(e.Value.ToString, iValue) Then

                If iValue >= 0 AndAlso iValue <= &HFF Then
                    e.Value = iValue  'value inside the range, accept it'
                Else
                    e.Value = cell.Value 'value outside the range, reload old value'
                End If

            Else                    
                e.Value = cell.Value 'invalid input, reload old value'
            End If

        End If

        e.ParsingApplied = True

    End Sub



回答2:


I would use the gridView actionevent CellValueChanged. If that is too late then use CellValueChanging



来源:https://stackoverflow.com/questions/3054767/datagridview-cell-editing-issue-with-decimal-hexadecimal-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!