TEXTBOX中怎么判断只能输入的是字母

解决方案 »

  1.   

    方法一:
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    string s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + (char)8;
    if(s.IndexOf(e.KeyChar.ToString()) < 0)
    {
    e.Handled = true;
    }
    }
    同时给textBox1加一个空的ContextMenu,用来屏蔽右键菜单。
      

  2.   

    方法二:
    private string oldvalue = "";
    private void textBox1_TextChanged(object sender, System.EventArgs e)
    {
    string s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for(int i = 0 ; i < textBox1.Text.Length ; i ++)
    {
    if(s.IndexOf(textBox1.Text[i]) < 0)
    {
    textBox1.Text = oldvalue;
    return;
    }
    }
    oldvalue = textBox1.Text;
    }
      

  3.   

    笨办法:去空格后截取最后一个字符,如果在A到z之间的,就为true,textBox1.Text的真就为oldvalue. 不用for也不用string,可以减少内存和cpu的开支。
      

  4.   

    private void button4_Click(object sender, System.EventArgs e)
      {
       //using System.Text.RegularExpressions;
       string str="23sd呜SDF呜95列gfwef随地56国GE嘎4";
       MatchCollection ms=Regex.Matches(str,"[\u4e00-\u9fa5]");
       string sss=null;
       for(int i=0;i   {
        sss+=ms[i].Value;
       }
       MessageBox.Show(sss);   if (Regex.IsMatch(str,"[0-9]"))//数字
        MessageBox.Show("字符串中包含有数字");
                if (Regex.IsMatch(str,"[a-z]"))//小写字母
        MessageBox.Show("字符串中包含有小写字母");
       if (Regex.IsMatch(str,"[A-Z]"))//大写字母
        MessageBox.Show("字符串中包含有小写字母");
       if (Regex.IsMatch(str,"[a-zA-Z]"))//所有字母
        MessageBox.Show("字符串中包含有字母");
                if (Regex.IsMatch(str,"[\u4e00-\u9fa5]"))//汉字
        MessageBox.Show("字符串中包含有汉字");
      }
      

  5.   

    private void textBox1_KeyPress(object sender, System.EventArgs e)
    {
        if ((e.KeyChar < (char)'a' && e.KeyChar > (char)'z') &&
            (e.KeyChar < (char)'A' && e.KeyChar > (char)'Z'))
        {
            e.KeyChar = 0;
        }
    }随手写的,可以用(char) '字母'的到ASCII码值,然后比较就行了。