tags:

views:

303

answers:

3

I'm trying to come up with a way to easilly detect if a change has been made to a control on a winform. This approach works but it provides no information about what controls have been changed. Is there a way to override the TextChanged event so it will pass and EventArg which contains the name of the control that fired the event? When AccountChangedHandler executed the sender paramter contains information about the textbox such as the current value of the '.Text' property but I don't see anything about which control raised the event.

private bool _dataChanged = false;

internal TestUserControl()
{
  InitializeComponent();

  txtBillAddress1.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtBillAddress2.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtBillZip.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtBillState.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtBillCity.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtCountry.TextChanged += new System.EventHandler(AccountChangedHandler);

  txtContactName.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtContactValue1.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtContactValue2.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtContactValue3.TextChanged += new System.EventHandler(AccountChangedHandler);
  txtContactValue4.TextChanged += new System.EventHandler(AccountChangedHandler);

}

private void AccountChangedHandler(object sender, EventArgs e)
{
  _dataChanged = true;
}
+5  A: 
void AccountChangedHandler(object sender, EventArgs e)
{
   string n = ((TextBox)sender).Name;
   string t = ((TextBox)sender).Text;
   // or instead of cast
   TextBox tb = sender as TextBox; // if sender is another type, tb is null
   if(tb != null)
   {
     string n = tb.Name;
     string t = tb.Text;
   }
}

Also you can try use

foreach (Control c in this.Controls)
{
 c.TextChanged += new EventHandler(AccountChangedHandler);
}
abatishchev
Ahhh -- so the reference is in sender! I was looking at sender in the debugger watch window but was not understanding much. You have to keep drilling down into '.base' untill you are at the inherited base class where the .Name property is defined.
If my post helped, could you please mark it as answer? Or give another question, I'll be happy to help you :)
abatishchev
+2  A: 

What about the sender parameter?

Gerrie Schenck
+2  A: 

sender is a reference to the control that raised the event. If you do

TextBox tb = sender as TextBox;
string name = tb.Name;

You'll see that now you can use "tb" just as if it were something like "txtContractName." If you want to do specific logic you could do something like

if(tb == txtBillAddress1) { ... }

However, at this point you'd probably be better off having a separate event handler.

Jeff Moser