Numbers Only in Textbox using C#

Today in C#, I will teach you how to create a program that accepts only number input in the textbox. There are many fields in an information that we must only type a number in a textfield or in a textbox such as phone number, zip code, or any fields that must have a number type only. So, now we will begin this filtering a textbox into number only. Now, let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application. 2. Next, add only one textBox named TextBox1 so that we can filter to input letters in the textbox. You must design your layout like this: design 3. Now put this code in your code module for Button1.
  1. public void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
  2. {
  3. if ((e.KeyChar < '0'|| e.KeyChar > '9') && e.KeyChar != ControlChars.Back && e.KeyChar != '.'&& e.KeyChar != ',')
  4. {
  5. //cancel key
  6. e.Handled = true;
  7. }
  8. }
We use keypress event in our Textbox because this event occurs when the user presses and releases an ANSI key. We use the variable e As System.Windows.Forms.KeyPressEventArgs and has a method name of KeyChar or a key character that will hold only a value from 0 to 9. The period (.) and comma(,) are included in the textbox because it is a part of the number system as we code the syntax:
  1. e.KeyChar != ControlChars.Back && e.KeyChar != '.'&& e.KeyChar != ','
Output: output For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Comments

Add new comment