views:

45

answers:

3

Say aspx page called theParent has a DataGrid control named theDataGrid and a UserControl named theUserControl , and theUserControl has a button named theUcButton .

Yes, I know, very imaginative naming.

When theUcButton is clicked , a session variable is changed.

This session variable is a select parameter for the datasource of theDataGrid.

However, because of the order of stuff called in the page lifecycle, when theUcButton is clicked and a postback is generated , theParent controls are loaded before theUserControl resets the session variable, and theDataGrid does not show the new data until the next postback .

How to I get what I want to work?

I am using 3.5 if that matters.

+1  A: 

You can declare an event as a member of the UserControl class, raise it, and handle it in the Page class.

You can also use other events like Page.PreRender() to pick up things after the user control's events.

joelt
I have been trying to get this to work with no success. Can you recommend an Events for Dummies link?
Lill Lansey
Not really...I'd just start Googling. A bit simpler method would be to create a public method on your page that binds the grid. Then the UserControl can do something along the lines of this.Page.MyBindingFunction(); I'm a VB guy, so the syntax may be off, and you probably have to cast this.Page to the correct class, but that should be the gist of it. This way makes the page and control more tightly coupled, which isn't great, but I think it's cleaner than using the prerender event.
joelt
Won't work. To call Page.MyBindingFunction would need to new an instance of Page which has all controls as null.
Lill Lansey
Why is the Page property of your UserControl not set?
joelt
A: 

The easiest way would be to hold off on the databind until the later in the lifecycle, such as the Page.PreRender event as joelt suggested. If you do the bind then, you should have the session variables.

Todd Friedlich
A: 

Here is example code for your user control to raise an event.

public partial class WebUserControl : System.Web.UI.UserControl{
public event EventHandler Updated;

protected void Button1_Click(object sender, EventArgs e)
{
    //do some work to this user control

    //raise the Updated event
    if (Updated != null)
        Updated(sender, e);
}}

Then from your .aspx page, you'll deal with the new event just like usual

    <uc1:WebUserControl ID="WebUserControl1" runat="server" OnUpdated="WebUserControl1_Updated" />

Code behind:

protected void WebUserControl1_Updated(object sender, EventArgs e)
{
    //handle the user control event
}
matt-dot-net