Tutorial :Send textbox name to custom method on text changed event


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?


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.


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.


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  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »