Reputation: 347
I would just like to know how to create a textbox that only allows the user to type numbers, one that allows numbers and a fullstops and one that only allows the user to type letters?
I used this code for Windows Form:
private void YearText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts numbers
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
{
e.Handled = true;
}
}
private void NameText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts letters
{
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
e.Handled = true;
}
private void ResellPriceText_KeyPress(object sender, KeyPressEventArgs e) //Textbox that allows only numbers and fullstops
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
But I soon found out this can't be done with WPF. I'm not fussed about things such as the ability to paste letters/numbers.
Upvotes: 4
Views: 3206
Reputation: 18118
This can be done in WPF, in fact you can even do it with very similar event handler based code, however, don't this - it is a terrible user experience. This will prevent users from copying and pasting when they accidentally include surrounding spaces and will prevent entering scientific numbers e.g. 100e3.
Instead use validations (on the trimmed input) and prevent the user from continuing if the validations fail.
Upvotes: 3