I don’t know if it will solve everything you want, but the solution is usually to use the MaskedTextBox
. If this doesn’t solve, either you have to create a control of your own (or you take a ready better than the default), or you have to do a lot of customization on it (it doesn’t always give the expected result).
If you insist on customizing TextBox
standard, to control everything that is needed is quite complicated to post an answer here.
Unless you just want to format at the end of the typing, then it’s simple, but the user experience will be badly impaired.
Another alternative to this specific case may be a NumericUpDown
. It’s up to you if you take it well.
To make something simple and only prevent the use of other characters, maybe this will solve:
private void textBox11_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != ',')) {
e.Handled = true;
MessageBox.Show("este campo aceita somente numero e virgula");
}
if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf('.') > -1)) {
e.Handled = true;
MessageBox.Show("este campo aceita somente uma virgula");
}
}
I put in the Github for future reference.
Why not use a Numericupdown? Just check the option for it to work with decimal and :D
– Ícaro Dantas