如何使文本框只接受a-z而不是其他?

时间:2016-06-05 19:00:11

标签: c# winforms textbox masking

我在Windows窗体中有4个文本框。我想将其更改为仅接受字母a到z的字母,而不是其他内容,即使粘贴了内容。如果用户粘贴了字母和不需要的字符,则只有字母应显示在文本框中。 / p>

我想要的最后一件事是numlock pad。这些数字与键盘顶部的数字行相同,但我也想让它们阻止它们!

4 个答案:

答案 0 :(得分:0)

我很确定应该有一些看起来像的语法; var isAlpha = char.IsLetter('text'); 您需要做的就是在文本框中实现语法,如图所示; var isAlpha = textbox.char.IsLetter('text');

答案 1 :(得分:0)

在ASCII表中,a-z的格式为97到122:

string str = "a string with some CAP letters and 123numbers";
void Start(){
    string result = KeepaToz(str);
    Debug.Log(result); // print "astringwithsomelettersandnumbers"
}
string KeepaToz(string input){
   StringBuilder sb = new StringBuilder();
   foreach(char c in str){
       if(c >= 97 && c<= 122){ sb.Append(c); }
   }
   return sb.ToString();
}

答案 2 :(得分:0)

我想假设引入一个源自TextBox的自定义控件,类似于this post

public class LettersTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        string c = e.KeyChar.ToString();

        if (e.KeyChar >= 'a' && e.KeyChar <= 'z' || char.IsControl(e.KeyChar))
            return;

        e.Handled = true;
    }

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        const int WM_PASTE = 0x0302;
        if (m.Msg == WM_PASTE)
        {
            string text = Clipboard.GetText();
            if (string.IsNullOrEmpty(text))
                return;

            if (text.Any(c => c < 'a' || c > 'z'))
            {
                if (text.Any(c => c >= 'a' || c <= 'z'))
                    SelectedText = new string(text.Where(c => c >= 'a' && c <= 'z').ToArray());
                return;
            }
        }
        base.WndProc(ref m);
    }
}

答案 3 :(得分:0)

使用TextChanged事件。类似的东西:

// Set which characters you allow here
private bool IsCharAllowed(char c)
{
    return (c >= 'a' && c <= 'z')
}    

private bool _parsingText = false;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    // if we changed the text from within this event, don't do anything
    if(_parsingText) return;

    var textBox = sender as TextBox;
    if(textBox == null) return;

    // if the string contains any not allowed characters
    if(textBox.Text.Any(x => !IsCharAllowed(x))
    {        
      // make sure we don't reenter this when changing the textbox's text
      _parsingText = true;
      // create a new string with only the allowed chars
      textBox.Text = new string(textBox.Text.Where(IsCharAllowed).ToArray());         
      _parsingText = false;
    }
}

您可以将此方法分配给每个文本框TextChanged个事件,并且只允许他们输入IsCharAllowed()中的内容(如果通过粘贴,通过打字,则无关紧要)触摸屏或其他)