CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: TextBox - Valid

  1. #1
    Join Date
    Feb 2002
    Posts
    10

    Question TextBox - Valid

    I'm doing a calculation program and I only want numbers to be typed in the TextBox.

    How do I make a validation so letters and other characters can't be typed.

    I thought this was simple but I can´t find the key.


    Thank you for the attention!

  2. #2
    Join Date
    Jun 2002
    Location
    Philadelphia, PA
    Posts
    85
    You will want to consume the TextBox.KeyPress event. You then check the value of the KeyPressEventArgs.KeyChar. If it's not within your range, you set e.handled = true.

    Here's a code snipped to better explain it:

    Code:
       void keypressed(Object o, KeyPressEventArgs e)
       {
          if(e.KeyChar < 'a' || e.KeyChar > 'z')
          {
            e.Handled = true;  // prevent from passing back to Windows for handling.
          }
             
       }
    HTH.

  3. #3
    Join Date
    Sep 2002
    Posts
    3
    The above method can only be used for System.Windows.Forms TextBox not for a webform textbox.

  4. #4
    Join Date
    Sep 2002
    Posts
    3
    Add this code to InitializeComponent() function:

    this.TextBox.KeyPress += new
    System.Windows.Forms.KeyPressEventHandler(this.TextBox_KeyPress);


    and this to the code:
    private void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if ((e.KeyChar!=(char)8)&&(e.KeyChar!=(char)32)&&(!Char.IsDigit(e.KeyChar)) )
    //the ASCII character code for SAPCE is 32 and BACKSAPCE is 8
    {
    e.Handled=true;
    }
    }

    the above fn will allow only digits, space and backspace to be typed in the textbox.
    Hope this helps.

  5. #5
    Join Date
    Feb 2002
    Posts
    10
    Thank you for your help!!

    It´s working fine. The program is a windows application but the goal is to make it a web application. As I´m a beginner at C#, I have to start somewhere.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured