开发者

Win Forms text box masks

How can I put mask on win form text box so that it allows only numb开发者_JAVA技巧ers? And how it works for another masks data, phone zip etc.

I am using Visual Studio 2008 C#

Thanks.


You can use the MaskedTextBox control

http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx


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.


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;

}


As said above, use a MaskedTextBox.

It's also worth using an ErrorProvider.


Use Mask Text box and assign MasktextboxId.Mask.

If u want to use textbox then you have to write Regular Expression for it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜