tags:

views:

47

answers:

2

My form has many textboxes. When one of the textboxes is changed, I want to send the textbox's name and its new value to a method. How do I go about this?

+1  A: 

Link the text box's "Text Changed" event to a function and then send that text box's members to the method:

private void myTxtbox_TextChanged(object sender, EventArgs e)
{
    //Call the method with the name and value of the text box
    myMethod(myTextBox.Name, myTextBox.Text);
}

Just do this for each text box in the form.

EDIT: HERE IS THE GENERIC CODE

Here is the generic code for the text box:

private void allTxtBox_TextChanged(object sender, EventArgs e)
{
    //'sender' is the text box who's text was just changed
    string name = ((TextBox)sender).Name;
    string text = ((TextBox)sender).Text; //This will be the new text in the text box

    //Call the method with the name and value of the text box
    myMethod(name, text);
}

Using this method just link the 'TextChanged' event of each text box to this one function. You can do it easily in the event editor in the Properties window in Visual Studio.

Mike Webb
If you make the handler generic (casing sender back to the original type rather than hardcoding myTextBox throughout), you can re-use the same handler for multiple text boxes rather than having to code a new one each time.
Justin Niessner
Thanks, Mike! Justin's suggestion about making the handler generic sounds terrific, but I don't know how to implement it.
+3  A: 

Register for the OnTextChanged event for the text boxes in question:

txtBox1.OnTextChanged += new TextChangedEventHandler(txtBox_OnTextChanged);
txtBox2.OnTextChanged += new TextChangedEventHandler(txtBox_OnTextChanged);
txtBox3.OnTextChanged += new TextChangedEventHandler(txtBox_OnTextChanged);
// And so on...

And then:

public void txtBox_OnTextChanged(object sender, EventArgs e)
{
    var textBox = (TextBox)sender;

    OtherMethod(textBox.Name, "Some New Value");
}

public void OtherMethod(string name, string value)
{
    // Do whatever here
}
Justin Niessner