CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Apr 2001
    Location
    Midwest
    Posts
    57

    Question preventing non-ints in a string

    How do you do this in C#? I'm used to making an edit-box in VC, and forcing it to only accept int values. Can't seem to find the way to do this in C#.

    Thanks,
    sternaphile
    "Judge a man by his questions rather than his answers." - Voltaire

  2. #2
    Join Date
    May 2002
    Location
    Florida USA
    Posts
    27
    Write a handler for KeyDown/KeyPress (not sure which, but one will work) in the text box. Check the value of the key. If not a number, stop processing i.e. .Handled()

    Bill F

  3. #3
    Join Date
    Apr 2001
    Location
    Midwest
    Posts
    57
    Sure, that would work, but how about something along the lines of isdigit()?
    "Judge a man by his questions rather than his answers." - Voltaire

  4. #4
    Join Date
    May 2002
    Location
    Florida USA
    Posts
    27
    As in using isdigit() to check the key? The KeyPress handler will return the key pressed. I'm sure there is a static function Keys.IsDigit() or some sort that could do that.

    Bill F

  5. #5
    Join Date
    Jun 2002
    Location
    Philadelphia, PA
    Posts
    85
    In your validation code(KeyPress or KeyDown), do the following:

    Code:
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
      if ((Char.IsDigit(e.KeyChar) == false) && (Char.IsControl(e.KeyChar) == false))
      {
        e.Handled = true;
      }
    }
    That chesk for digits(0-9) and control keys(arrows, delete, etc). Hope that helps!

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