Search code examples
c#.neteventspaginationdelegates

Calling page event when ASP.NET user control event is invoked


Suppose there is a user control in a page called Paging.ascx that is embedded in PageWithResults.aspx. This control has the necessary properties to keep track of various details about what page you're on (ie: CurrentPage, TotalRecordsInResults, RecordsPerPage, etc..). It also contains events that fire off when you click on a hyperlink ("next page" or "previous page"). Example below. I need to tell PageWithResults.aspx that one of these LinkButton web controls was clicked. I think I need to assign a delegate in the page, so that when this user control event is called (hyperlink is clicked), it also calls some other method/event in the page class. That way I can quickly check what the new value of CurrentPage is (based on what was called in the event below) and get a new result set for the new page (based on the CurrentPage property). But I'm not sure of the best approach. I'm thinking this will require a delegate, but I'm not sure how to wire it up. If you need more details, please ask.

    protected void btnNext_Click(object sender, EventArgs e)
    {
        this.CurrentPage = this.CurrentPage + 1;
        if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
    }

I'm thinking I have to put my delegate here somewhere. ??

    protected void btnNext_Click(object sender, EventArgs e)
    {
        this.CurrentPage = this.CurrentPage + 1;
        if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
                    //delegate to call object.method or something
    }

Solution

  • Using an event would work fine.

    You would create the event within your UserControl like so:

    public event EventHandler ButtonClicked;
    

    Then invoke the event when required:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ButtonClicked != null)
            ButtonClicked(this, new EventArgs());
    }
    

    In your page you would need to assign an event handler:

    protected void Page_Load(object sender, EventArgs e)
    {
        UserControl1.ButtonClicked += new EventHandler(UserControl1_ButtonClicked);
    }
    
    void UserControl1_ButtonClicked(object sender, EventArgs e)
    {
    
    }
    

    As well as using the above approach you can also cast the Page reference in the UserControl and call a public method directly:

    MyPage page = (MyPage)Page;
    page.AMethod();
    

    Hope this helps.