C# App: Numeric and Mathimatical Operators only TextBox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • LoanB
    New Member
    • Nov 2007
    • 62

    C# App: Numeric and Mathimatical Operators only TextBox

    Hi

    I'm looking to ensure that my textbox only accepts numbers .. AND ... mathematical operators + - . / *. an dmaybe a blank space

    I can ensure that only number are included by using:
    [code=cpp]
    private void txtSurname_KeyP ress(object sender, KeyPressEventAr gs e)
    {
    if (e.Handled = !(Char.IsDigit( e.KeyChar)))
    {
    e.Handled = true;
    }
    }[/code]

    OR
    [code=cpp]
    private void txtTel_KeyPress (object sender, KeyPressEventAr gs e)
    {
    if (((e.KeyChar < '0') || (e.KeyChar > '9')) && (e.KeyChar != '\b'))
    {
    e.Handled = true;
    }
    }
    [/code]
    My Questions then:

    1. Which one of the above is better to use to ensure that only numbers are
    used?

    2. How can I change the better option above to also allow me to input the
    specified operators.

    Thanks in advance,

    Lóan
    Last edited by Frinavale; Nov 30 '07, 06:49 PM. Reason: Added [code] tags
  • LoanB
    New Member
    • Nov 2007
    • 62

    #2
    Ok I managed to get it working doing the following,
    [code=cpp]
    private void txtTel_KeyPress (object sender, KeyPressEventAr gs e)
    {
    if ((e.Handled = !(Char.IsDigit( e.KeyChar))) && (e.Handled =
    !(Char.IsWhiteS pace(e.KeyChar) )) && (e.Handled =
    !(Char.IsPunctu ation(e.KeyChar ))) && (e.Handled =
    !(Char.IsSymbol (e.KeyChar))) && (e.Handled = !(Char.IsContro l(e.KeyChar))))
    {
    e.Handled = true;
    }
    }
    [/code]
    this works perfectly, but does anyone know how to do th eabove in a shorter version.

    Cheers,

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Originally posted by LoanB
      Ok I managed to get it working doing the following,
      [code=cpp]
      private void txtTel_KeyPress (object sender, KeyPressEventAr gs e)
      {
      if ((e.Handled = !(Char.IsDigit( e.KeyChar))) && (e.Handled =
      !(Char.IsWhiteS pace(e.KeyChar) )) && (e.Handled =
      !(Char.IsPunctu ation(e.KeyChar ))) && (e.Handled =
      !(Char.IsSymbol (e.KeyChar))) && (e.Handled = !(Char.IsContro l(e.KeyChar))))
      {
      e.Handled = true;
      }
      }
      [/code]
      this works perfectly, but does anyone know how to do th eabove in a shorter version.

      Cheers,
      The above will work for a desktop application.
      If you're developing a web application please see the article on how to check if a textbox contains a number.

      -Frinny

      Comment

      • LoanB
        New Member
        • Nov 2007
        • 62

        #4
        Thanks mate

        That will be very helpful next week when I start with the WEB stuff.

        Comment

        Working...