简体   繁体   English

如何在C#winforms中为表单上的多个文本框控件调用Text_Changed事件

[英]How call the Text_Changed Event for multiple text box controls on a form in C# winforms

I have form that has about 20 TextBox controls and I would like to fire the Text_Changed event with out adding the event for each individual text box. 我的表单有大约20个TextBox控件,我想激发Text_Changed事件,而不是为每个单独的文本框添加事件。 Is there a way to loop through the text boxes to fire this event? 有没有办法循环文本框来触发此事件? What I am trying to do is clear a label control when the text changes. 我想要做的是在文本更改时清除标签控件。 Instead of displaying a message box, for error descriptions, I use a label control to display the message. 我没有显示消息框,而是使用标签控件来显示消息。 I also set it up where if a text box has invalid data, I select all text and give focus to that TextBox so when user re-enters information the label control clears the message. 我还设置了如果文本框包含无效数据的地方,我选择所有文本并将焦点放在该TextBox这样当用户重新输入信息时,标签控件就会清除消息。

Edit: 编辑:

To clear up some confusion, here is some of my code from my validation method 为了解决一些困惑,这里是我的验证方法中的一些代码

if (txtBentLeadsQty.Text == "")
{
    //ValidData = true;
    BentLeadsCount = 0;
}
else 
{
    if (int.TryParse(txtBentLeadsQty.Text.Trim(), out BentLeadsCount))
        ValidData = true;
    else
    {
        ValidData = false;
        lblError.Text = "Bent Lead Qty must be a numeric value";
        txtBentLeadsQty.SelectAll();
        txtBentLeadsQty.Focus();
    }
}

I already have a way to check for numeric values, and I put code in to select all text entered and gave focus if the values are not numeric, I just want to have a way to clear the Label control when the the text is changes like if the user hit backspace or starts typing that why if the error occurs, I highlight all the text in that TextBox if it is not valid. 我已经有办法检查数值,并且我输入代码来选择所有输入的文本并在值不是数字时给予焦点,我只想在文本更改时清除Label控件的方法如果用户点击退格键或开始输入错误发生的原因,我会突出显示该TextBox所有文本(如果它无效)。 I can do this if I put code in every text boxes TextChanged event, but to save coding I was wondering if there is way to clear the label control if any of the text boxes throws an error from my validation method instead of adding individual events for 20 text boxes. 如果我在每个文本框TextChanged事件中放置代码,我可以这样做,但是为了保存编码,我想知道是否有办法清除标签控件,如果任何文本框从我的验证方法抛出错误而不是添加单个事件20个文本框。

Note: Not all text boxes will have data entered, these are quantity text boxes I put code in to assign a 0 to the variable if the TextBox in null. 注意:并非所有文本框都会输入数据,如果TextBox为null,这些是我放入代码的数量文本框,为变量赋值0。

You can use the following code: 您可以使用以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls)
    {
        if ((ctrl as TextBox) != null)
        {
            (ctrl as TextBox).TextChanged += Form1_TextChanged;
        }
    }
}
private void Form1_TextChanged(object sender, EventArgs e)
{
    MessageBox.Show((sender as TextBox).Name);
}

I'm assuming you want to add the same handler to all textboxes in the form dynamically, ie without having to add them for each text box in the visual editor (or code). 我假设您想要动态地向表单中的所有文本框添加相同的处理程序,即无需为可视编辑器(或代码)中的每个文本框添加它们。

If so, this might be what you need: 如果是这样,这可能就是您所需要的:

// Iterate over all controls in the current form:
foreach (var ctl in Controls)
{
    // Check if the current control is a textbox 
    // (will be null if it is of another type)
    var txtBox = ctl as TextBox;
    if (txtBox != null)
    {
        txtBox.TextChanged += YourMethod();
    }
}

Sounds like you want to programmatically fire the method on each text box. 听起来好像你想以编程方式在每个文本框上触发方法。

First, create an array of around 20 text boxes. 首先,创建一个包含大约20个文本框的数组。

var textBoxes = new []{textBox0, textBox1, textBox2};

Loop through the each box and call the text changed method 循环遍历每个框并调用文本更改的方法

foreach(var textBox in textBoxes)
{
     TextChangedMethod(textBox);
}

If the method you are calling was generated by Visual Studio, it will take a second parameter for EventArgs. 如果您调用的方法是由Visual Studio生成的,则它将为EventArgs采用第二个参数。 You can simply pass a null value for that. 您可以简单地为其传递null值。

TextChangedMethod(textBox, null);

Create a method, something like this: 创建一个方法,如下所示:

public void TextChanged(object sender, EventArgs e)
{
    //Text-changed code here.
}

At this point you can click on each text box on your form and add your new method to the event you want to occur. 此时,您可以单击表单上的每个文本框,并将新方法添加到要发生的事件中。 Click a text box on your form, and click the thunderbolt icon in the properties menu and scroll down to "TextChanged" event. 单击表单上的文本框,然后单击属性菜单中的thunderbolt图标并向下滚动到“TextChanged”事件。 Change that drop down on that event to your new method. 将该事件的下拉列表更改为新方法。

OR 要么

Add the event at run time after you initialize the forms components: 初始化表单组件后,在运行时添加事件:

textBox1.TextChanged += new EventHandler(TextChanged);
textBox2.TextChanged += new EventHandler(TextChanged);
textBox3.TextChanged += new EventHandler(TextChanged);

This could be done easier if you add all the text boxes to an array, and loop through them with a foreach to add the event to each one. 如果将所有文本框添加到数组中,并使用foreach循环遍历它们以将事件添加到每个文本框,则可以更轻松地完成此操作。 You could also just grab all the text boxes from the form and loop the same way, though I don't know if you have other controls/text boxes that would make you avoid this method. 您也可以从表单中获取所有文本框并以相同的方式循环,但我不知道您是否有其他控件/文本框可以让您避免使用此方法。

Use a foreach statement. 使用foreach语句。

Example

List<TextBox> TextblockCollection = null;//You have to add them all individually to the list
foreach (var text in TextblockCollection)
{
    //Change the text to the same thing, firing the method
    text.Text = text.Text
}

So you want to check when any of the text boxes are changed, then check if the new input in the changed textbox is a number (I'm assuming an integer) and then display a message in a label if it's not a number. 因此,您要检查何时更改了任何文本框,然后检查更改的文本框中的新输入是否为数字(我假设为整数),然后在标签中显示消息(如果它不是数字)。

public MainForm()
{
    InitializeComponent();

    foreach (Control control in this.Controls)
    {
        if (typeof(control)==typeof(TextBox))
        {
            (control as TextBox).TextChanged += CommonHandler_TextChanged;
        }
    }
}

private void CommonHandler_TextChanged(object sender, EventArgs e)
{
    int number;
    string input=(sender as TextBox).Text;
    bool isnumber=false;
    isnumber = Int32.TryParse(input, number);
    if(isnumber==false)
    {
        yourLabel.Text = "This textbox contains an incorrect number: "
                         +(sender as TextBox).Name;
    }
    else{ /*use the number*/ }
}

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

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