简体   繁体   English

C#计算多个文本框的字符

[英]c# count characters of multiple text boxes

I have two (and going to be more but for this example I will keep it to two) text boxes that I want to total the character count into one label. 我有两个文本框(但在本示例中,我将保留两个),我希望将字符计数总计到一个标签中。

The two text boxes I have are called probDescTextbox and stepsToRepoTextbox. 我拥有的两个文本框分别称为probDescTextbox和stepsToRepoTextbox。

I am using winforms and a TextChanged event. 我正在使用winforms和TextChanged事件。 I am not sure if there is a way to get this to work without having multiple TextChanged events but if i nest it i get an error and if i make a second one, i cannot seem to get the numbers to add. 我不确定是否有一种方法可以在没有多个TextChanged事件的情况下正常工作,但是如果我将其嵌套,则会收到错误消息,并且如果我进行第二次操作,则似乎无法获取数字。

CODE: 码:

    private void probDescTextBox_TextChanged(object sender, EventArgs e)
    {
        int probDescLimit = probDescTextBox.Text.Length;
        int stepsToRepoLimit = stepsToRepoTextBox.Text.Length;
        int charLimit = probDescLimit + stepsToRepoLimit;

        if (charLimit >= 50)
        {
            probDescCharLabel.ForeColor = Color.Red;
            probDescCharLabel.Text = charLimit.ToString() + " Over Limit!!";
        }
        else
        {
            probDescCharLabel.ForeColor = Color.Black;
            probDescCharLabel.Text = charLimit.ToString();
        }
    }

I am sure this is simple enough but I cannot find an example using multiple text boxes. 我确信这很简单,但是我找不到使用多个文本框的示例。

Thanks in advance. 提前致谢。

You could wire the text change event to the same handler. 您可以将文本更改事件连接到同一处理程序。

Edit: 编辑:

1.) Change the name of your event handler to something more generic so that you know it's not specific to the probDescTextBox : 1.)将事件处理程序的名称更改为更通用的名称,以使您知道它不是特定于probDescTextBox

 private void note_TextChanged(object sender, EventArgs e)
    {
       //Same code as you have above, or see note...
    }

Note : If you need to know which textbox fired the event see the answer here . 注意 :如果您需要知道哪个文本框触发了事件,请在此处查看答案。 You can inspect the sender. 您可以检查发件人。 This will allow you to only set the forecolor of the textbox which fired the event. 这将允许您仅设置触发事件的文本框的前色。

2.) Wire up the event handler in your form's constructor as shown below, or if you're using the designer, change the values in each text box's properties window: 2)如下图所示,将事件处理程序连接到窗体的构造函数中,或者,如果您使用的是设计器,请在每个文本框的属性窗口中更改值:

public MyForm()
{
     //wire each textbox's TextChanged event to the same handler
     probDescTextBox.TextChanged += note_TextChanged;
     stepsToRepoTextbox.TextChanged += note_TextChanged;
}

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

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