DataGridView单元格编辑问题与十进制/十六进制格式 [英] DataGridView Cell Editing issue with decimal/hexadecimal formatting
问题描述
我有一个 DataGridView 绑定到一个 DataTable ,其中有1 + 16列定义为整数。
I have a DataGridView bound to a DataTable that has 1+16 columns defined as Integer.
默认单元格样式为十六进制2位数( .Format =X2
)。
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.
- 十六进制可以写成像例如0x00,0X01,x02,XFF
- 小数像0,1,2,15
为此,在 EditingControlShowing 中,我将0x添加到TextBox值
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
而在 TextBox_KeyPress 子我执行所有输入过滤以避免无效输入。
while in TextBox_KeyPress sub I perform all input filtering to avoid invalid inputs.
我不明白的是,我可以附加哪个事件,以便在编辑完成时检测。我想要与 EditingControlShowing 相反的东西,以便我可以删除0x,但没有找到它。
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.
推荐答案
在TextBox和DataGRidView中尝试所有可能的事件后,我终于找到一个对我的情况有用的。
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
这篇关于DataGridView单元格编辑问题与十进制/十六进制格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!