Question

I have a Page.aspx that is being re-used. Sort of like a Master Page (I'm actually using Sitecore CMS, so it works like a master Page even if it is not and I cannot use this.parent). On a certain instance, I have a ASCX control loading on that Page needs to do some special processing. It needs to hide/show a banner that lies on the Page.aspx.

I'm thinking one of the options could be to have an event fire on the ASCX and it can be implemented on the Page.aspx in order to determine whether the banner is shown or not.

Now this shouldn't break in case other controls in the Page do not use the event. Can this be accomplished? do you have any other ideas as to how to accomplish this behavior?

Was it helpful?

Solution 4

You can bubble up the event from user control to the parent. For example,

ParentAddUser.aspx

<uc1:AddUser ID="AddUser1" runat="Server" OnUserCreated="AddUser1_UserCreated">
</uc1:AddUser>

ParentAddUser.aspx.cs

protected void AddUser1_UserCreated(object sender, CommandEventArgs e)
{
    // User was created successfully. Do Something here.
}

AddUser.ascx.cs

public event CommandEventHandler UserCreated;

protected void Button_Click(object sender, EventArgs e)
{
    // Create a user
    ...

    // User was created successfully, so bubble up the event to parent. 
    UserCreated(this, new CommandEventArgs("UserId", userId.ToString()));
}

OTHER TIPS

You should use events like you've suggested. This approach allows the implementation to be generic, reusable, and loosely coupled.

Another way to do it within user control itself by referencing parent Page. This way code is confined within user control code. Something like

Control oBanner = this.Page.FindControl("BannerID");

if (oBanner != null) {
  oBanner.Visible = false;
}

I agree with @freeasinbeer that you should go with an event. But for future reference, you can always access the page from the user control and call any public functions.

You just have to cast the Page object.

        if (Page.GetType().BaseType.Name == "PageName")
        {
            ((PageName)Page).PublicFunction();
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top