简体   繁体   中英

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. 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.

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. 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.

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.

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.

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. You can simply pass a null value for that.

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. 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. 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.

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*/ }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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