简体   繁体   English

C#-限制文本框中的某些字符

[英]c# - limit certain characters inside textbox

I am trying to limit the amount of a certain character (in my case a comma (,)) inside my textbox. 我试图限制文本框内某个字符(在我的情况下为逗号(,))的数量。 I want it to only allow max 9 commas in the textbox. 我希望它在文本框中最多允许9个逗号。 If the user attempts to add more commas than 9, it should display a messagebox with the error, and then also not allow the user to enter more into the textbox. 如果用户尝试添加多于9个逗号,则应显示带有错误的消息框,然后也不允许用户在文本框中输入更多逗号。

In my application, I allow the user to add 10 tags to a textbox separated by commas. 在我的应用程序中,我允许用户将10个标签添加到以逗号分隔的文本框中。

An example input by the user could look like this: summer,sexy,hot,beautiful,girls,guys,food,music,funny,lol 用户输入的示例可能看起来像这样: summer,sexy,hot,beautiful,girls,guys,food,music,funny,lol

That is the max limit of tags allowed in the textbox (9 commas). 这是文本框中允许的标签的最大限制(9个逗号)。 And when they reach that limit, it should block them from typing any more commas. 并且当它们达到该限制时,应该阻止他们再输入逗号。 I hope I was clear enough. 我希望我足够清楚。

Here is my code so far. 到目前为止,这是我的代码。 My textbox is called tagBox. 我的文本框称为tagBox。

private void tagBox_TextChanged(object sender, EventArgs e)
        {
            // Allow max 10 tags in the tag box
            string tags = tagBox.Text;
            int count = tags.Split(',').Length - 1;
            if (count > 9)
            {
                MessageBox.Show("Max 10 tags are allowed.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

I only managed to make the messagebox appear. 我只设法使消息框出现。 But how do I stop them from typing in more commas? 但是,如何阻止他们输入更多逗号?

It should look something like this: 它看起来应该像这样:

private void tagBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Allow max 10 tags in the tag box
    string tags = tagBox.Text;
    int count = tags.Split(',').Length - 1;
    if (count > 9 && e.KeyChar == ',')
    {
        e.Handled = true;
        MessageBox.Show("Max 10 tags are allowed.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    else        
        e.Handled = false;
}

I think you should do something like this 我认为你应该做这样的事情

    Public class TagTextBox : TextBox
    {
        Public override OnKeyDown(object sender, KeyEventArgs args)
        {
            // Do logic here
            // Call this to accept Key
            base.OnKeyDown(sender, args);
         }
    }

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

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