User Control Events
I have a user control with a button开发者_如何学JAVA named upload in it. The button click event looks like this:
protected void btnUpload_Click(object sender, EventArgs e)
{
// Upload the files to the server
}
On the page where the user control is present, after the user clicks on the upload button I want to perform some operation right after the button click event code is executed in the user control. How do I tap into the click event after it has completed its work?
You have to create an event in your user control, something like:
public event EventHandler ButtonClicked;
and then in your method fire the event...
protected void btnUpload_Click(object sender, EventArgs e)
{
// Upload the files to the server
if(ButtonClicked!=null)
ButtonClicked(this,e);
}
Then you will be able to attach to the ButtonClicked event of your user control.
Create a Public Property in UserControl's CodeBehind:
public Button btn
{
get { return this.Button1; }
}
Then on page_Load you can use it like:
WebUserControl11.btn.Click += (s, ea) => { Response.Write("Page Write"); };
Instead of writing an event handler just to call another event, you can instead directly wire the events together by using an explicit event implementation:
public event EventHandler ButtonClicked
{
add { btnUpload.Click += value; }
remove { btnUpload.Click -= value; }
}
Now anyone who subscribes to your ButtonClicked
event is actually directly subscribing to the Click
event of the btnUpload
control. I find this to be a much more succinct way to implement this.
精彩评论