简体   繁体   English

C# - 仅包含字母和数字的文本框

[英]C# - Textbox with only letters and numbers

How can I limit my textbox to only accept numbers and letters? 如何限制我的文本框只接受数字和字母? It should not even allow spaces or anything like "!", "?", "/" and so on. 它甚至不应该允许空格或类似“!”,“?”,“/”之类的东西。 Only az, AZ, 0-9 只有az,AZ,0-9

Tried this and it did not work at all 试过这个,它根本不起作用

if (System.Text.RegularExpressions.Regex.IsMatch(@"^[a-zA-Z0-9\_]+", txtTag.Text))
{
    txtTag.Text.Remove(txtTag.Text.Length - 1);
}

Not even sure if that txtTag.Text.Remove(txtTag.Text.Length - 1); 甚至不确定那个txtTag.Text.Remove(txtTag.Text.Length - 1); should be there because it makes the application crash. 应该在那里,因为它使应用程序崩溃。

You don't need a regex for that: 您不需要正则表达式:

        textBox1.Text = string.Concat(textBox1.Text.Where(char.IsLetterOrDigit));

This will remove everything that is not a letter or digit, and can be placed in the TextChanged event. 这将删除所有不是字母或数字的内容,并且可以将其放置在TextChanged事件中。 Basically, it gets the text, splits it into characters and only pick what is a letter or digit. 基本上,它获取文本,将其拆分为字符,仅选择字母或数字。 After that, we can concatenate it back to a string. 之后,我们可以将其连接回字符串。

Also, if you'd like to place the caret at the end of the textbox (because changing the text will reset its position to 0), you may also add textBox1.SelectionStart = textBox1.Text.Length + 1; 另外,如果您想将插入符号放在文本框的末尾(因为更改文本会将其位置重置为0),则还可以添加textBox1.SelectionStart = textBox1.Text.Length + 1;

My thought is you could alter the KeyPressed or TextChanged events for that control to check if the characters entered are numbers or letters. 我的想法是你可以改变该控件的KeyPressedTextChanged事件,以检查输入的字符是数字还是字母。 For example, to check the characters as they are added in the textbox you could do something like the following : 例如,要检查在文本框中添加的字符,可以执行以下操作:

myTextbox.KeyPress += new KeyPressEventHandler(myTextbox_KeyPress);



void myTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= Keys.A && e.KeyChar <= Keys.Z)

    // you can then modify the text box text here

try this 尝试这个

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)
             && !char.IsSeparator(e.KeyChar) && !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
    }

First of all, check out this article for some information. 首先,查看本文以获取一些信息。

I think what you should do on the client side is to add the pattern attribute in the corresponding HTML. 我认为您应该在客户端执行的操作是在相应的HTML中添加pattern属性。

<input type="text" name="foo" pattern="[a-zA-Z0-9_]" title="Please input only letters and numbers">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM