【问题标题】:How to make a TextBox accept only alphabetic characters?如何使 TextBox 只接受字母字符?
【发布时间】:2012-01-09 10:45:50
【问题描述】:

如何让TextBox 只接受带空格的字母字符?

【问题讨论】:

    标签: c# winforms textbox


    【解决方案1】:

    您可以使用以下 sn-p:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
        {
            MessageBox.Show("This textbox accepts only alphabetical characters");
            textBox1.Text.Remove(textBox1.Text.Length - 1);
        }
    }
    

    【讨论】:

    • 似乎不太好用。如果我添加一个字母,然后添加一个数字/空格/任何它会让我满意的正则表达式(以字母开头)。
    • @favoretti 现在代码可以正常工作,但是如果我键入第一个字符整数并且当我按下退格键删除它时会发生异常。代码适用于数字,当我输入数字时它会弹出消息。但是当我尝试用退格键清除时,它给了我错误 StartIndex 不能小于零,参数名称 startIndex。如何处理?
    【解决方案2】:

    您可以尝试处理文本框的KeyPress 事件

    void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
    }
    

    另外说允许退格,以防你想删除一些文本,这对你来说应该很好

    编辑

    上面的代码不适用于粘贴在我认为您必须使用TextChanged 事件的字段中,但是您必须删除不正确的字符或突出显示它并放置它会有点复杂供用户进行更正的光标或者您可以在用户输入完整的文本并关闭控件后进行验证。

    【讨论】:

    • 这个效果很好,但它不允许我粘贴应该通过验证的文本。
    【解决方案3】:

    最简单的方法是处理 TextChangedEvent 并检查输入的内容:

    string oldText = string.Empty;
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (textBox2.Text.All(chr => char.IsLetter(chr)))
            {
                oldText = textBox2.Text;
                textBox2.Text = oldText;
    
                textBox2.BackColor = System.Drawing.Color.White;
                textBox2.ForeColor = System.Drawing.Color.Black;
            }
            else
            {
                textBox2.Text = oldText;
                textBox2.BackColor = System.Drawing.Color.Red;
                textBox2.ForeColor = System.Drawing.Color.White;
            }
            textBox2.SelectionStart = textBox2.Text.Length;
        }
    

    如果您愿意,这是一个无正则表达式的版本。它会使文本框在输入错误时闪烁。 请注意,它似乎也支持粘贴操作。

    【讨论】:

    • 先生,那太好了,但你能详细告诉我打字是如何自动停止的吗?只是 if 循环检查,但打字是如何停止的?关于 lambda 表达式? textBox1.Text.All(chr => char.IsLetter(chr)) 这是怎么回事。如果可以,请表示这是如何工作的
    • 嘿!那么它的作用是将输入中的先前文本存储在 oldText 变量中。然后在随后更改文本框时,它会逐个字符地检查字符,如果字符不是字母 - 它会返回旧文本。如果是 - 它将旧文本设置为与当前(新)文本框输入相同。因此,如果您有一个有效的输入 - oldText 获取的是 TextBox 值,如果您有无效的输出 - 它会以相反的方式工作。此外,一些 GUI 样式有助于可视化是否存在错误。希望这会有所帮助。
    • 因此,即使一个字符不是字母,textBox2.Text.All() lambda 也会返回 false。如果都是字母 - 它将返回 true。从那时起,上面的解释就发生了。
    【解决方案4】:
            if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
            { 
            }
            else
            {
                textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
                MessageBox.Show("Enter only Alphabets");
    
    
            }
    

    请试试这个

    【讨论】:

      【解决方案5】:

      在 Text_KeyPress 事件中编写代码为

       private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
          {
      
              if (!char.IsLetter(e.KeyChar))
              {
                  e.Handled = true;
              }
          }
      

      【讨论】:

        【解决方案6】:
        private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.A && e.Key <= Key.Z)
            {
            }
            else
            {
               e.Handled = true;
            }
        }
        

        【讨论】:

          【解决方案7】:
          private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
                  {
                      if (e.KeyChar >= '0' && e.KeyChar <= '9')
                          e.Handled = true;
                      else
                          e.Handled = false;
                  }
          

          【讨论】:

          • 请说明您的答案为何有效以及如何将文本框连接到您的活动。
          【解决方案8】:

          这个工作非常好......

           private void manufacturerOrSupplierTextBox_KeyPress(object sender, KeyPressEventArgs e)
              {
                  if (char.IsControl(e.KeyChar) || char.IsLetter(e.KeyChar))
                  {
                      return;
                  }
                  e.Handled = true;
              }
          

          【讨论】:

          • 感谢 IsControl 检查。
          【解决方案9】:
          private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
              {
                if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) &&
                   (e.KeyChar !='.'))
                  { 
                    e.Handled = true;
                    MessageBox.Show("Only Alphabets");
                  }
              }
          

          【讨论】:

          • 更好地解释你的解决方案
          【解决方案10】:

          试试这个

                      private void tbCustomerName_KeyPress(object sender, KeyPressEventArgs e)
              {
                  e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back||e.KeyChar==(char)Keys.Space);
              }
          

          它也允许空格

          【讨论】:

            【解决方案11】:

            您可以尝试以下在按键事件时发出警报的代码

            private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
                {
            
                    //===================to accept only charactrs & space/backspace=============================================
            
                    if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
                    {
                        e.Handled = true;
                        base.OnKeyPress(e);
                        MessageBox.Show("enter characters only");
                    }
            

            【讨论】:

              【解决方案12】:

              这是我的解决方案,它按计划工作:

              string errmsg = "ERROR : Wrong input";
              ErrorLbl.Text = errmsg;
              
              if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
              {
                ErrorLbl.Text = "ERROR : Wrong input";
              }
              else ErrorLbl.Text = string.Empty;
              if (ErrorLbl.Text == errmsg)
              {
                Nametxt.Text = string.Empty;
              }
              

              【讨论】:

                【解决方案13】:

                在文本框的 KeyPress 事件中尝试以下代码

                if (char.IsLetter(e.KeyChar) == false  & 
                        Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
                            e.Handled = true
                

                【讨论】:

                  【解决方案14】:

                  此方案使用正则表达式,不允许将无效字符粘贴到文本框中并保持光标位置。

                  using System.Text.RegularExpressions;
                  
                  int CursorWas;
                  string WhatItWas;
                  
                  private void textBox1_Enter(object sender, EventArgs e)
                      {
                          WhatItWas = textBox1.Text;
                      }
                  
                  private void textBox1_TextChanged(object sender, EventArgs e)
                      {
                          if (Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$"))
                          {
                              WhatItWas = textBox1.Text;
                          }
                          else
                          {
                              CursorWas = textBox1.SelectionStart == 0 ? 0 : textBox1.SelectionStart - 1;
                              textBox1.Text = WhatItWas;
                              textBox1.SelectionStart = CursorWas;
                          }
                      }
                  

                  注意:textBox1_TextChanged 递归调用。

                  【讨论】:

                    【解决方案15】:

                    就字符限制而言,这可以正常工作,如果不是 C OR L,任何关于错误消息的建议都会提示我的代码

                    Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged
                    
                            Dim allowed As String = "C,L"
                            For Each C As Char In TXTBOX.Text
                                If allowed.Contains(C) = False Then
                    
                                    TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
                                    TXTBOX.Select(TXTBOX.Text.Count, 0)
                    
                                End If
                    
                            Next
                          
                        End Sub
                    

                    【讨论】:

                      【解决方案16】:

                      对我有用,虽然不是最简单的。

                      private void Alpha_Click(object sender, EventArgs e)
                              {
                                  int count = 0;
                                  foreach (char letter in inputTXT.Text)
                                  {
                                      if (Char.IsLetter(letter))
                                      {
                                          count++;
                                      }
                                      else
                                      {
                                          count = 0;
                                      }
                                  }
                                  if (count != inputTXT.Text.Length)
                                  {
                                      errorBox.Text = "The input text must contain only alphabetic characters";
                                  }
                                  else
                                  {
                                      errorBox.Text = "";
                                  }
                              }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2010-10-21
                        • 2016-07-26
                        • 2011-04-17
                        • 1970-01-01
                        • 1970-01-01
                        • 2014-06-06
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多