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开发者_如何学Go.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();
)
You can add your own control to the toolbox and drop it on the form designer.
with event KeyPress
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar != (char)Keys.Back ? e.KeyChar.ToString() : "0", out isNumber);
}
精彩评论