Reputation: 9925
How can I put mask on win form text box so that it allows only numbers? And how it works for another masks data, phone zip etc.
I am using Visual Studio 2008 C#
Thanks.
Upvotes: 6
Views: 28908
Reputation: 4905
Control the user's key press event to mask the input by not allowing any unwanted characters.
To allow only numbers with decimals:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
To allow only phone numbers values:
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
if (e.KeyChar == 8) return;
e.Handled = true;
}
Upvotes: 1
Reputation: 177
Use Mask Text box and assign MasktextboxId.Mask.
If u want to use textbox then you have to write Regular Expression for it
Upvotes: -1
Reputation: 2273
As said above, use a MaskedTextBox.
It's also worth using an ErrorProvider.
Upvotes: -1
Reputation: 839144
Do you want to prevent input that isn't allowed or validate the input before it is possible to proceed?
The former could confuse users when they press keys but nothing happens. It is usually better to show their keypresses but display a warning that the input is currently invalid. It's probably also quite complicated to set up for masking an email-address regular expression for example.
Look at ErrorProvider to allow the user to type what they want but show warnings as they type.
For your first suggestion of a text box that only allows numbers, you might also want to consider a NumericUpDown.
Upvotes: 3
Reputation: 5507
You can use the MaskedTextBox control
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Upvotes: 5