tags:

views:

50

answers:

2

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.

+1  A: 

You can add your own control to the toolbox and drop it on the form designer.

Giorgi
+1  A: 

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();)

serhio
Thanks serhio. The codeproject link is really helpful. i had forgotton that numbers can be enetered through num keypad too... Designer... i guess creating a new dll that has the customized textbox class and then drag and dropping teh new control is the only way to avoid the constant changes in the winform or designer.
Maneesh
normally, as I said, you can replace your textboxes manually changing the designer code, but not like you do: `private MyTextbox myTextBox = new MyTextBox();`, but like designer does with other controls `private MyTextBox myTextBox;` and anly then `myTextBox = new MyTextBox();` - 2 different non consecutive lines.
serhio