代码之家  ›  专栏  ›  技术社区  ›  Drake

使用十进制/十六进制格式的DataGridView单元格编辑问题

  •  2
  • Drake  · 技术社区  · 14 年前

    我有一个 数据表格控件 绑定到 可计算的 其中1+16列定义为 整数 .

    默认单元格样式为十六进制2位数字( .Format="X2" )

    在进入单元格编辑时,我想向用户提供以十进制或十六进制写入值的可能性。

    1. 十六进制可以写为,例如,0x00、0x01、X02、XFF
    2. 十进制,如0、1、2、15

    因为这个原因 编辑控件显示 我将“0x”添加到文本框值

    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
    

    而在 文本框按键 Sub I执行所有输入过滤以避免无效输入。

    我无法理解的是,当编辑完成时,我可以附加到哪个事件来检测。我想要和…相反的东西 编辑控件显示 这样我就可以删除“0x”,但我没有找到它。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Drake    14 年前

    在尝试了文本框和DataGridView中所有可能的事件之后,我终于找到了一个对我的案例有用的事件。

    细胞分析

    我复制了我的代码,也许它可以帮助其他人:)

       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
  •  0
  •   Kyra    14 年前

    我将使用GridView ActionEvent CellValueChanged。如果太晚,请使用CellValueChanging

    推荐文章