Finding Characters in a TextBox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinay307
    New Member
    • Mar 2010
    • 4

    Finding Characters in a TextBox

    I am working on windows application. My requirement is in my application I am retrieving text files and displaying the contents of text files in text box, but here i want to display text files which contains only numeric data. Where as in my application it will display numeric data as well as alphabets. How can i check text box does it contains numeric data or alphabets?
  • Bassem
    Contributor
    • Dec 2008
    • 344

    #2
    Hi,

    You can try to convert the retrieved string to double, if it works assign the string to the textbox.Text.
    Code:
                string s = "1.0";
                try
                {
                    Convert.ToDouble(s);
                    textBox1.Text = s;
                }
                catch 
                {
                    // don't.
                }

    Comment

    • GaryTexmo
      Recognized Expert Top Contributor
      • Jul 2009
      • 1501

      #3
      I'm a fan of the double.TryParse method myself... it doesn't have the overhead of a try/catch.

      example...
      Code:
      string sPi = "3.14159";
      double dPi;
      if (double.TryParse(sPi, out dPi))
      {
        // success
      }
      else
      {
        // failure
      }
      Note, you don't necessarily have to have the if statement there... only if you want to tell if the conversion was successful. Hope that helps.

      Comment

      • ThatThatGuy
        Recognized Expert Contributor
        • Jul 2009
        • 453

        #4
        Instead of everyhing else you just need to use regular expressions.... in checking whether the text fetched from the file contains only numbers...

        Code:
        Regex reg=new Regex("[0-9]*");
        if(reg.IsMatch("fetched Data")
        {
        //display in textbox
        }

        Comment

        • Bassem
          Contributor
          • Dec 2008
          • 344

          #5
          Yes, the last is the best.

          Thanks ThatThatGuy, I'll use this one.

          >>Edited

          Don't forget the floating point numbers!

          <<
          Last edited by Bassem; Mar 8 '10, 09:48 PM. Reason: Adding a floating note :)

          Comment

          • vinay307
            New Member
            • Mar 2010
            • 4

            #6
            Thank U for giving me this solution.

            Comment

            Working...