VS 2008 Remove all character except numbers and decimals?-VBForums
Results 1 to 3 of 3

Thread: Remove all character except numbers and decimals?

  1. #1

    Thread Starter
    Hyperactive Member DerekM's Avatar
    Join Date
    Jun 2009
    Location
    Colorado
    Posts
    296

    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.

  2. #2
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,531

    Re: Remove all character except numbers and decimals?

    Here is one way using LINQ.
    vb.net Code:
    1. Dim nums = From c In TextBox1.Text _
    2.     Where Char.IsDigit(c) OrElse c = "." _
    3.     Select num = c.ToString
    4. 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.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  3. #3
    Addicted Member
    Join Date
    Jul 2009
    Posts
    138

    Re: Remove all character except numbers and decimals?

    Assuming you only want valid decimals, this would be a better approach:

    vb.net Code:
    1. Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    2.     If sender.Text <> String.Empty Then
    3.         Dim TypedNumber As String = sender.Text
    4.         Dim NumberRegex As String = "^[0-9]+\.?[0-9]*$"
    5.         If Not System.Text.RegularExpressions.Regex.Match(TypedNumber, NumberRegex).Success Then
    6.             sender.Text = sender.Text.Remove(sender.Text.Length - 1, 1)
    7.             sender.SelectionStart = sender.Text.Length
    8.         End If
    9.     End If
    10. 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
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.