Skip to content

Keypress style for alphanumeric textbox help plz.

ankur

Asked Apr 6, 2006, 5:50 PM EDT1 answer
Share
LinkedInX
hi,
i am very very new to C# and although i am used to VB 6 and a bit of C++ and JAVA.. i cant seem to find how to control the inputs on a text field.
i need a filter for my textbox that only accepts alpha numeric input.
i was thinking over the line of  having a keypress event and checking at textbox_change that each char is alphanumeric. how to do this. plz can anyone give me a skeleton or the textbox_TextChanged function!?
I am using Framework 1.1 i think thats why i dont even have the maskedtextbox commponent to help me :-P..
plz reply asap!
thanks...

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    there are actually a few ways to do this. one involves overriding the textbox control.  The other, (quick and dirty and less OO oriented way) is to:

    1) Set the form property KeyPreview = true

    this.KeyPreview = true;

    2) place your textbox in the form

    3) hook up the textbox event handler for keypress

    this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

    4) override the event handler textBox1_KeyPress as shown below:

    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
     {
       char nextChar = (char)e.KeyChar;
       Regex patternMatters = new Regex("[0-9A-Za-z_]+");
       if (patternMatters.Match(nextChar.ToString()).Success)
        {
            e.Handled = false;
        }
      else
       {
         e.Handled = true;
       }

     }


    5) Don't forget to add the using statement for regular expression use

    using System.Text.RegularExpressions;


    Hope this helps!

    -Mike G.  (Microsoft MVP)




    0