Search code examples
c#.net-3.5

By default make TextBox to accept numeric values only


I referred to StackOverflow post here: How do I make a textbox that only accepts numbers?

The problem with this style is that I need to add code or a method call to this code in every TextBox's Keypress event.

I want it in a different way. I want to modify the TextBox class itself in such a way that it can be made to accept either a string or a number depending upon criteria, as and when TextBox control is dropped from the ToolBox on the Form.


Solution

  • Don't create a user control, simply derive a new class from TextBox. Add a new class to your project and get started with code like this:

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    
    class NumberBox : TextBox {
        // insert code here
    }
    

    After you compile, the new control appears at the top of the toolbox.