|
-
Sep 5th, 2009, 05:32 PM
#1
Thread Starter
Hyperactive Member
Remove all character except numbers and decimals?
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.
-
Sep 5th, 2009, 06:30 PM
#2
Re: Remove all character except numbers and decimals?
Here is one way using LINQ.
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, "")
You may put this in the TextChanged event, with whatever customization you need, if you do not want this textbox to accept anything else.
-
Sep 5th, 2009, 06:43 PM
#3
Addicted Member
Re: Remove all character except numbers and decimals?
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]*$"
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|