I want to know if there is an easy and short way to remove all characters except for numbers and decimals from a string. Either that or have a textbox that will only except numbers and decimals, but not a masked textbox.
Printable View
I want to know if there is an easy and short way to remove all characters except for numbers and decimals from a string. Either that or have a textbox that will only except numbers and decimals, but not a masked textbox.
Here is one way using LINQ.
You may put this in the TextChanged event, with whatever customization you need, if you do not want this textbox to accept anything else.vb.net Code:
Dim nums = From c In TextBox1.Text _ Where Char.IsDigit(c) OrElse c = "." _ Select num = c.ToString TextBox1.Text = Join(nums.ToArray, "")
Assuming you only want valid decimals, this would be a better approach:
vb.net Code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged If sender.Text <> String.Empty Then Dim TypedNumber As String = sender.Text Dim NumberRegex As String = "^[0-9]+\.?[0-9]*$" If Not System.Text.RegularExpressions.Regex.Match(TypedNumber, NumberRegex).Success Then sender.Text = sender.Text.Remove(sender.Text.Length - 1, 1) sender.SelectionStart = sender.Text.Length End If End If End Sub
Edit: This would require decimals less than 1 to be typed as "0.5" instead of ".5". If that's a problem just change NumberRegex to "^[0-9]*\.?[0-9]*$"