Hello,
EDIT : if you want to have the final version of the custom control, go to the last post.
For one of my application, I had to restrict some textbox entry to numeric only but I accept scientific notation (so 1E5 is ok) and negative value (so the - sign is ok too) and as some of the users have a config that use coma and others that use dot as decimal separator, I dealt also with that. I wanted also that if you type any non valid key, nothing happen (in appearance)
I created 2 functions and worked on the textchanged event.
Function to Check that the text is a number
Code:Public Function verif_nombre(ByVal text As String) As String Dim count As Integer 'To count the number of E Dim text_verifie As String = "" Dim l As Integer = text.Length If l = 0 Then Return text_verifie ' If there is no character, do go further, it is not needed Dim charac As Char = text.Chars(text.Length - 1) ' get the last character typed If charac = CChar("-") And text.Length = 1 Then ' deal with - sign Return text End If If text.Contains(" ") Then ' replace space by nothing text = text.Replace(" ", "") Return text End If 'Count the number of e or E in the text If text.Contains("e") And text.Contains("E") Then count = 2 ElseIf text.Contains("e") Then count = text.Split(CChar("e")).Length - 1 ElseIf text.Contains("E") Then count = text.Split(CChar("E")).Length - 1 End If If count = 1 And (charac = CChar("E") Or charac = CChar("e")) And l > 1 Then 'Deal with the scientific notation text_verifie = text Else If IsNumeric(text) Then ' verify that the text is numeric text_verifie = text Else text = text.Remove(l - 1) 'if not then remove last charac typed text_verifie = text End If End If Return text_verifie End Function
Manage dot and coma for the number
Code:Public Function gpv(ByVal text As String) As String 'GPV : gère point-virgule = manage dot - coma ;) Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo 'get the info on the decimal separator for the current user If nfi.NumberDecimalSeparator = "." Then 'if dot replace all coma by dot text = text.Replace(",", ".") Else 'if coma replace dot by coma text = text.Replace(".", ",") End If Return text End Function
Method to manage the TextChanged event
On the loading of the forms I handle the event for all textbox based on a tag, if the tag = num then I change the event methodCode:Public Sub Numeric_TextBox_TextChanged(sender As Object, e As System.EventArgs) Dim TB As TextBox = CType(sender, TextBox) TB.Text = verif_nombre(gpv(TB.Text)).ToString TB.Select(TB.Text.Length, 0) End Sub
Code:Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load For Each TB As TextBox In Me.Controls.OfType(Of TextBox)() If TB.Tag Is "num" Then AddHandler TB.TextChanged, AddressOf Numeric_TextBox_TextChanged End If Next End Sub




)
Reply With Quote