Skip to main content

Posts

Showing posts from December, 2013

How do I make a textbox that only accepts numbers?

How do I make a textbox that only accepts numbers? private void textBox1_KeyPress( object sender, KeyPressEventArgs e) {     if (! char . IsControl (e. KeyChar )         && ! char . IsDigit (e. KeyChar )         && e. KeyChar != '.' )     {         e. Handled = true ;     }     // only allow one decimal point     if (e. KeyChar == '.'         && (sender as TextBox ). Text . IndexOf ( '.' ) > - 1 )     {         e. Handled = true ;     } } Or use this  private void textBox1_TextChanged ( object sender , EventArgs e )     {         if ( System . Text . RegularExpressions . Regex . IsMatch ( "[^0-9]" , textBox1 . Text ))         {             MessageBox . Show ( "Please enter only numbers." );             textBox1 . Text . Remove ( textBox1 . Text . Length - 1 );         }     }