Friday, October 1, 2010

ASP Net - User Control Postback

I have a simple user control with a text box and a submit button. When the
user enters some text into the textbox and clicks the submit button, a
record is created in the database.

I'm using this user control inside another webform. The webform has a "Next"
button which is initially disabled. When the user control successfully adds
a record I want the Next button on the webform to get enabled.

Checking if the record was added successfully (return the count of a sql
query) in the Page_Load of the webform is too soon, since the Page_Load
event of the webform is raised before anything happens on the user control.

How can my user control "notify" my webform that it has successfully
completed postback?






Response:






You are putting too much work into this. Use RaiseBubbleEvent to
communicate to the parent that a click has been executed. While
creating your own events and handlers certainly make sense in some
cases, for simple child to parent communication, intrinsic event
management should suffice.

So:

Bind the button click to some delegate in your control, for instance:

this.btnDoSearch.Click += new
System.Web.UI.ImageClickEventHandler(this.btnDoSea rch_Click);

In the delegate method, raise the bubble event:

private void btnDoSearch_Click(object sender,
System.Web.UI.ImageClickEventArgs e)
{
RaiseBubbleEvent(this, e);
}

Then, in your parent, capture the bubbled event.

protected override bool OnBubbleEvent(object sender, EventArgs e)
{
nextButton.Visible = true

return true;
}

This is of course a short, raw version of the idea. You'll probably
modify it to your own needs and make it more robust. For instance, you
should check the sender object to ensure that the bubble event is coming
from the correct control. Also, you might want to create your own
custom event arguments, CommandEventArgs for instance, that you could
use to send more information about your control's click event to the parent.

Makes sense?

No comments:

Post a Comment