I want to edit a datagridview cell to be able to write decimals numbers but with only a dot for decimals separator, BUT if the user try to write a dot as a separator, I want to change the dot for a comma in the textbox cell.
For example, if I want to write in the datagridview cell the number 45.6 (it is usual in my country to write this number like 45,6 or 45.6 ) the system should do:
1st step: User writes 4, and in the dgv cell appears a 4
2nd step: User writes 5, and in the dgv cell we have a 45
3rd step: User Writes '.' but before it is printed in the cell, the system change it for a ',' and in the cell we have 45,
4th step: User tries to write another '.' (or another ','), but the systems control it and doesn't write anything in the cell. We still have 45,
5th step: User writes '5', and in the cell we finally have a 45,6
I have tried to use the EditingControlShowing to get the textbox in the dgv:
Private Sub dgv_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
If TypeOf e.Control Is TextBox AndAlso dgv.CurrentCell.ColumnIndex = 3 Then
Dim textBox As TextBox = DirectCast(e.Control, TextBox)
AddHandler textBox.KeyPress, AddressOf DataGridViewTextBox_KeyPress
AddHandler textBox.KeyDown, AddressOf DataGridViewCell_KeyDown
End If
End Sub
The KeyPress event to change dot for comma
Private Sub DataGridViewTextBox_KeyPress(sender As Object, e As KeyPressEventArgs)
If e.KeyChar = "."c Then
e.KeyChar = ","c
End If
End Sub
And the KeyDown event to control the format of the input string
Private Sub DataGridViewCell_KeyDown(sender As Object, e As KeyEventArgs)
Dim nonNumberEntered As Boolean = False
' Checking keys to write decimal numbers: numbers, comma and delete key for corrections...
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
If e.KeyCode <> Keys.Back Then
If e.KeyCode <> Keys.Oemcomma Then
nonNumberEntered = True
End If
End If
End If
End If
Dim currentTextBox As TextBox = CType(sender, TextBox)
Dim currentText As String = currentTextBox.Text
' Check if the entered text matches the regular expression
Dim inputRegex As New Regex("^[0-9]+([,][0-9]+)?$")
Dim isValidInput As Boolean = inputRegex.IsMatch(currentText)
If Not isValidInput Then
nonNumberEntered = True
End If
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
End If
End Sub
I could solve it using Double.TryParse to the input string, but i don't want to give an error message to the user and asking him to write a number in a correct format, I really want not to let him to write wrong strings directly.
I have also tried other events (CellValidating, TextChanged...) but not succesfully. Even ChatGPT couldn't help me (probably my fault explaining my needs).
Maybe can any human ^^ help me with this? (VB or C# is ok) Thanks for your time!