Win Forms text box masks

佐手、 提交于 2020-01-01 05:27:26

问题


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.


回答1:


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.




回答2:


You can use the MaskedTextBox control

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




回答3:


You might want to check out How to: Create a Numeric Text Box.




回答4:


As said above, use a MaskedTextBox.

It's also worth using an ErrorProvider.




回答5:


Use Mask Text box and assign MasktextboxId.Mask.

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




回答6:


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;

}


来源:https://stackoverflow.com/questions/2259850/win-forms-text-box-masks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!