siva siva - 1 month ago 5x
C# Question

create a textbox that accepts only numeric values. Problem with designer mode

i have a form that has some six - seven text boxes. few text boxes needs to accept only numeric chars i.e from 0-9, a decimal poing and + or -

i handled the textbox key press event

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
if (!char.IsControl(e.KeyChar)

&& !char.IsDigit(e.KeyChar)

&& e.KeyChar != '.')
e.Handled = true;


Now i have to write the same code for all the textboxes which i felt is redudant.
I created a new class MyTextBox derived from TextBox and added the above code into it.

In the designer mode i drag and drop the textbox control .. go to the Designer.cs file and change the line to

private MyTextbox m_txtName = new MytextBox();

Now the problem is that if i add a new button or any control to teh form the designer.cs file is changed/updated... and the aboe line is changed to the normal TextBox and i got to go replace this everytime ... can i avoid this ?

Note: I do not want to use MasktextBox or numericKeydown control.


An excellent example you will find here.

As about designer. When you will rebuild your project, you will(should) see your textBox as a custom component in the Toolbox. Drag and drop that component instead of your ancient textBoxes.

If not, you need to find all the references of your MyTextBox1 because you need to change it in at least 2 places: declaration and creation(MyTextBox mtb; and mtb = new MyTextBox();)