Search code examples
asp.neteventsmaster-pagesonload

How to handle master page button event in content page?


My problem is this I have a base page that creates content dynamically. There are buttons on my Master Page that fire events that my base page needs to know about. But the OnLoad function on my base page fires before my Button_Command function on my master page. So I either need to figure out a way to load my base page after the Button_Command function has had the chance to set a variable or I must call a function in my base page from the Button_Command function.


Solution

  • I believe you can do this with an interface

    public interface ICommandable
    {
        public void DoCommand1(object argument);
    }
    

    So the child page implements this interface

    public class MyPage : Page, ICommandable
    {
        public void DoCommand1(object argument) {
    
        }
    }
    

    And on the master page

    public class Master : MasterPage
    {
        public void Button_Command(object sender, EventArgs e)
        {
            if (Page is ICommandable)
            {
                (Page as ICommandable).DoCommand1(myargument);
            }
            else
                throw new NotImplementedException("The current page does not implement ICommandable");
        }
    }
    

    It has been a long time since I worked with webforms however, so I can't swear that this works. I seem to recall writing something like this before.