I have a master page where in I have a link button. In one of the content pages, I need to hide the linkbutton and replace with image button. The click event handler for image button should exactly do the same thing as the click event of the link button in master page. So is there a way of calling the Master page link button click event handler from the Image button click event handler in Content page?
I have researched and there seem to be a lot in case Master page wants to call the event handler in Content page…
Any inout will be highly appreciated.
Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In your master page’s code behind replace the protected keyword on the event handler to public.
public void LinkButton1_Click(object sender, EventArgs e)
{
//Do Stuff Here
}
IN your content page use the Master Type Directive
<%@ MasterType VirtualPath="~/masters/SourcePage.master"" %>
In the code behind for the content page call the Master event handler as follows
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
this.Master.LinkButton1_Click(sender, e);
}
Note the code is C#.
I’m looking into calling the master pages event handler more directly
Method 2
There is also the @ Master directive (MSDN Article). This method provides a way to create a strongly typed reference to the ASP.NET master page when the master page is accessed from the Master property.
The result is as stated strongly typed and there is no need to cast.
Example usage:
<%@ MasterType VirtualPath="~/masters/SourcePage.master"" %>
Using this directive actually produces the same code as @Scott’s implementation but does not require you to know the type of the masterpage.
You can then start using your masterpage by lets say:
Master.Title = "My Page Title";
You will be able to invoke events from the master this way as well. Use Master.FindControl to find the master control you want.
Example of find control:
HtmlAnchor btnMyImageButton = (HtmlAnchor)Master.FindControl("btnMyImageButton");
BUT I would suggest using the OnClick property of the ImageButton and set it to a publicly accessible void/Sub on the Master page. Then simply call that void/Sub like:
Master.ImageButtonClick();
Method 3
If your Master Page is MyMaster, make a property like this:
Public Shadows ReadOnly Property Master() As MyMaster
Get
Return CType(MyBase.Master, MyMaster)
End Get
End Property
Then whatever you want to access in the Master Page, make sure it’s Public, and you will be able to access it via:
Master.xxxx
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0