有一个MaskedTextBox中只接受字母 [英] Having a MaskedTextBox only accept letters

查看:184
本文介绍了有一个MaskedTextBox中只接受字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

如何设置它只接受字母, ?非常感谢!

解决方案

如果屏蔽文本框接受regualr表达式,

您可以使用可选字母掩码并投入相同的金额(尽管不是很漂亮)作为您在文本框中允许的最大长度,即

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

或者,您可以使用自己的验证而不是掩码,并使用正则表达式, >

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

还有一种方法是忽略任何按键通过处理 KeyPress 事件,而不是来自字母的事件

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


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!

解决方案

This would be easy if masked text boxes accepted regualr 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 (!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(textbox1.Text, @"^[a-zA-Z]+$"))
          e.Handled = true;
}

这篇关于有一个MaskedTextBox中只接受字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆