C# Custom control – TextBox accepting only numbers, decimal numbers, signed numbers

| | | | |

The creation of custom control using Visual Studio involves the following steps:

  1. Start Visual Studio;
  2. Create new “Windows Control Library” project;
  3. In the created project delete “User Control” file;
  4. Go to “Project” > “Add User Control” and give it a name;
  5. Change the inherited class to this that you want your control to be;
  6. Create you custom properties for the control;
  7. Compile the project: Go to “Build” > “Build Solution”;
The generated DLL file is located in you projects folder under:“bin/Debug/UserContolName.dll” or “bin/Release/UserContolName.dll”.That depends on how your solution is configured: “Debug mode” or “Release mode”.

C# Textbox - enter only positive numbers on KeyPress event in Windows form application

| | |

To prevent users from entering incorrect data in Windows form application, set restriction to allow only specific characters to be entered in the text box.

This example uses KeyPress event to monitor the users input and to apply the restriction required.
To avoid code duplication in Windows multiform applications for example, a separate class file is created “CommonFunctions.cs”.

The function to allow only numbers in textbox control is named InputNumbers.

For each Windows form, create a single KeyPress event and call the InputNumbers function inside it.