Having a MaskedTextBox only accept letters

六眼飞鱼酱① 提交于 2019-12-11 03:22:52

问题


Here's my code:

private void Form1_Load(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "*[L]";
    maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
}

How can I set it to accept only letters, but however many the user wants? Thanks!


回答1:


This would be easy if masked text boxes accepted regular expression, but unfortunately they don't.

One (albeit not very pretty) way you could do it is to use the optional letter ? mask and put in the same amount as the maximum length you'll allow in the text box, i.e

maskedTextBox1.Mask = "????????????????????????????????.......";

Alternatively you could use your own validation instead of a mask and use a regular expression like so

void textbox1_Validating(object sender, CancelEventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, @"^[a-zA-Z]+$"))
    {
        MessageBox.Show("Please enter letters only");
    }
}

Or yet another way would be to ignore any key presses other than those from letters by handling the KeyPress event, which in my opinion would be the best way to go.

private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"^[a-zA-Z]+$"))
          e.Handled = true;
}



回答2:


If you want only letters to be entered you can use this in keyPress event

if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)) //The latter is for enabling control keys like CTRL and backspace
{
     e.Handled = true;
}


来源:https://stackoverflow.com/questions/4285653/having-a-maskedtextbox-only-accept-letters

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