User Control Event Sender

I have a control that extends UserControl. This control contains two ComboBox controls. I created an event handler that fires when any of the combos change:


public event EventHandler ComboChanged
{
add { cmbA.SelectedIndexChanged += value; cmbB.SelectedIndexChanged += value; }
remove {...}
}

When I add an event handler to this event, is there a way to senderdisplay as a user control (i.e. the parent ComboBox control) and not the ComboBox itself? Or am I trying to do something that I should not do here?

+3
source share
2 answers

You should have something like this:

public event EventHandler MyControlChanged

userControl ComboBox

protected void oncmbA_SelectedIndexChanged(object sender, EventArgs e)
{
   if (MyControlChanged!=null)
     MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}

protected void oncmbB_SelectedIndexChanged(object sender, EventArgs e)
{
   if (MyControlChanged!=null)
     MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}

UserControl, combobox, UserControl.

+3

Yoann - . , .

// Default listener makes null-check unnecessary when raising event.
// Note that no custom implementations are provided for add, remove.
public event EventHandler ComboChanged = delegate { };

...

foreach(var comboxBox in new[] {cmbA, cmbA})
{
  // Attach listener to combo-box event that raises our own event.
  // Lambda-expression is ok since we don't intend to ever unsubscribe.
  comboBox.SelectedIndexChanged += (sender, args) => ComboChanged(this, args);
}
+3

Source: https://habr.com/ru/post/1773008/


All Articles