C#: force TextBox to only Enter Number

person Jason Huangfolder_openC#, Codelocal_offer, , , , access_time April 22, 2010

Normally, Textbox Control would allow any text. If you want to restrict it to only enter numbers, you don’t need to use a MaskEdit, you need to simply add a handler for the event KeyPress on the TextBox, and set e.Handled to true only when it’s number that is being key in.

        private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (bNumeric && e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
            {
                e.Handled = true;
            }
        }

Comment

  1. thx for your sharing code 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>