Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. TextBox. How to Validate for Number??

TextBox. How to Validate for Number??

Scheduled Pinned Locked Moved C#
questiontutorial
9 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • . Offline
    . Offline
    ...---...
    wrote on last edited by
    #1

    I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

    D A N L A 5 Replies Last reply
    0
    • . ...---...

      I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

      D Offline
      D Offline
      Dan Neely
      wrote on last edited by
      #2

      Void OnButtonClick(...) { Try { int i = Convert.ToInt(textbox.Text); } catch { return } DoSomething(); }

      . 1 Reply Last reply
      0
      • D Dan Neely

        Void OnButtonClick(...) { Try { int i = Convert.ToInt(textbox.Text); } catch { return } DoSomething(); }

        . Offline
        . Offline
        ...---...
        wrote on last edited by
        #3

        Dan- thanks. I have already tried the code you've shown. My problem is that BOTH text boxes are "tied" to the button event-- so I keep getting an infnite loop of two MessageBoxes (each from the catch statements of the two TextBoxes) when there is an invalid entry....

        D 1 Reply Last reply
        0
        • . ...---...

          Dan- thanks. I have already tried the code you've shown. My problem is that BOTH text boxes are "tied" to the button event-- so I keep getting an infnite loop of two MessageBoxes (each from the catch statements of the two TextBoxes) when there is an invalid entry....

          D Offline
          D Offline
          Dan Neely
          wrote on last edited by
          #4

          I'm not sure I follow you here. Are you doing your check event when the button is clicked, or when a user modifies the content of eitehr box?

          A 1 Reply Last reply
          0
          • D Dan Neely

            I'm not sure I follow you here. Are you doing your check event when the button is clicked, or when a user modifies the content of eitehr box?

            A Offline
            A Offline
            Anonymous
            wrote on last edited by
            #5

            Ok Here's what I did...program crashes on invalid input and I get endless Message boxes that won't close on 'OK'. Thanks... This is driving me nuts....:confused: /////////////////////////////// void DrawComplexNumber1(Graphics g) { Pen p = c_xy.GetNextPen(); p.DashStyle = DashStyle.Dot; c_xy.SetOrigin(xIndent + graphRect.Width/2, yIndent + graphRect.Y/2); try { cmplxValue1.Real = Convert.ToDouble(textComplex_1Real.Text); } catch { MessageBox.Show("Error!"); } try { cmplxValue1.Imaginary = Convert.ToDouble(textComplex_1Imaginary.Text); } catch { MessageBox.Show("Error!"); } g.DrawLine(p, 250, 250, (float)(250 + (xIndent * cmplxValue1.Real)), (float)(250 - (yIndent * cmplxValue1.Imaginary))); ////////////////////////////////////////////// private void complex_1OK_Click_1(object sender, System.EventArgs e) { drawLine1 = !drawLine1; Invalidate(); } /////////////////////////////////////////Paint Handler .... if(drawLine1) DrawComplexNumber1(e.Graphics); }

            1 Reply Last reply
            0
            • . ...---...

              I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

              A Offline
              A Offline
              Anonymous
              wrote on last edited by
              #6

              hi How about using int32.parse(textbox.text) ? Banshi Khinchi

              1 Reply Last reply
              0
              • . ...---...

                I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

                N Offline
                N Offline
                nps_ltv
                wrote on last edited by
                #7

                You see the following code : private void button1_Click(object sender, System.EventArgs e) { int number = 0; try { number = System.Convert.ToInt32(textBox1.Text); } catch(Exception ex) { System.Windows.Forms.MessageBox.Show("Input is not a number !"); textBox1.Focus(); return; } DoSomething(number); } private void DoSomething(int iNumber) { // Your code is here ... } with textBox1, textBox2 are two instances of TextBox class and button1 is a instance of Button class. NPS.

                1 Reply Last reply
                0
                • . ...---...

                  I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

                  L Offline
                  L Offline
                  Luis Alonso Ramos
                  wrote on last edited by
                  #8

                  Handle the Validating event for both text boxes:

                  private void TextBox_Validating(object sender, CancelEventArgs e)
                  {
                      TextBox textBox = sender as TextBox;
                      if(textBox == null)  // Ensure this is indeed a TextBox
                          return;
                   
                      // Allow the user to leave the text box without typing anything
                      if(textBox.TextLength == 0)
                          return;
                   
                      bool error = false;
                   
                      try
                      {
                          int n = Convert.ToInt32(textBox);
                          if(n < 0 || n > 100)  // Check range if necessary
                              error = true;
                      }
                      catch(FormatException)
                      {
                          // Could not parse the number
                          error = true;
                      }
                      finally
                      {
                          if(error)
                          {
                              MessageBox.Show("Please enter a valid number");
                   
                              textBox.SelectAll();
                              textBox.Focus();
                   
                              e.Cancel = true;  // Don't allow focus to leave the control
                          }
                      }
                  }
                  

                  When the user tries to take focus away from the control, its contents will be validated. If invalid, the user won't be allowed to leave the control unless he corrects it or leaves it empty. Then in you button handler, just validate that the text boxes have anything. If they do, it's surely a valid number. I hope this helps! -- LuisR


                  Luis Alonso Ramos Intelectix - Chihuahua, Mexico Not much here: My CP Blog!

                  The amount of sleep the average person needs is five more minutes. -- Vikram A Punathambekar, Aug. 11, 2005

                  1 Reply Last reply
                  0
                  • . ...---...

                    I have two TextBoxes. I have a button that calls a method that will use the input from the text boxes ONLY if a number is entered. How do I do I do this? Tried for several nights-- but I keep crashing on non-numerical input... --thanks in advance

                    A Offline
                    A Offline
                    albCode
                    wrote on last edited by
                    #9

                    In keypress of textbox-es write this code: e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; u are able to write only numers no other charachters I hope this helps u

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups