How to work with delegates and event handler for u

2020-02-09 11:28发布

问题:

I have created a user control that contains a button. I am using this control on my winform which will be loaded at run time after fetching data from database.

Now I need to remove a row from a datatable on the Click event of that button.

The problem is that how do I capture that event in my form. Currently it goes in that user control's btn click event defination.

回答1:

You can create your own delegate event by doing the following within your user control:

public event UserControlClickHandler InnerButtonClick;
public delegate void UserControlClickHandler (object sender, EventArgs e);

You call the event from your handler using the following:

protected void YourButton_Click(object sender, EventArgs e)
{
   if (this.InnerButtonClick != null)
   {
      this.InnerButtonClick(sender, e);
   }
}

Then you can hook into the event using

UserControl.InnerButtonClick+= // Etc.


回答2:

It's not necessary to declare a new delegate. In your user control:

public class MyControl : UserControl
{
  public event EventHandler InnerButtonClick;
  public MyControl()
  {
    InitializeComponent();
    innerButton.Click += new EventHandler(innerButton_Click);
  }
  private void innerButton_Click(object sender, EventArgs e)
  {
    if (InnerButtonClick != null)
    {
      InnerButtonClick(this, e); // or possibly InnerButtonClick(innerButton, e); depending on what you want the sender to be
    }
  }
}


回答3:

Just modernizing ChéDon's answer, here is how you can do it in 2018:

public class MyControl : UserControl
{
  public event EventHandler InnerButtonClick;

  public MyControl()
  {
    InitializeComponent();
    innerButton.Click += innerButton_Click;
  }

  private void innerButton_Click(object sender, EventArgs e)
  {
      InnerButtonClick?.Invoke(this, e);
      //or
      InnerButtonClick?.Invoke(innerButton, e); 
      //depending on what you want the sender to be
  }
}