1

I have this in my Master page:

<asp:ContentPlaceHolder ID="BannerPlaceHolder" runat="server">              
 <asp:HyperLink ID="PortalBanner" runat="server" 
                ImageUrl="Images/banner-12-5-11.jpg"   
                NavigateUrl="~/Default.aspx"></asp:HyperLink>
</asp:ContentPlaceHolder>

I want to be able to change the hyperlink ImageUrl but I get a null exception:

Object reference not set to an instance of an object.

Here's my code to access the HyperLink

ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.Master.FindControl("BannerPlaceHolder");
HyperLink hp= (HyperLink)cp.FindControl("PortalBanner");
John Saunders
  • 157,405
  • 24
  • 229
  • 388
meda
  • 43,711
  • 13
  • 85
  • 120
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 13 '13 at 02:35

1 Answers1

2

Are you sure that it is in the Master of the Master? If not, simply change it to:

ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.FindControl("BannerPlaceHolder");

Another approach is to provide a property in your master that you can access from your page by casting it to the actual type.

in the master's codebehind:

public string PortalBannerImageUrl
{
    get {
        return this.PortalBanner.ImageUrl;
    }
    set {
        this.PortalBanner.ImageUrl = value;
    }
}

in the page:

var myMaster = this.Master as YourMasterType;
if(myMaster != null)
{
    myMaster.PortalBannerImageUrl = newImageUrl;
}
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • Thanks , you're right I had to remove the extra Master, is your second approach better then the first one? – meda Oct 08 '13 at 21:27
  • 1
    @meda: It's also hard-wiring the page with the master which is not so good. But it's clearer and less error-prone since it doesn't rely on an ID that might change. So yes, the second approach is normally better even if it's a little bit more work.You have even intellisense on this property and the name is self-explanatory. So if you (or others) want to access or change this property from other pages as well it's more readable and maintainable and you have compile time safety. – Tim Schmelter Oct 08 '13 at 21:29
  • Okay I get it, but what is `YourMasterType`? – meda Oct 08 '13 at 21:35
  • @meda: Since i didn't know the name of your `MasterPage` i have called it `YourMasterType`. Maybe it's `SiteMaster` or whatever. The name of the class that inherits `System.Web.UI.MasterPage` where you've declared the `ImageButton`. – Tim Schmelter Oct 08 '13 at 21:37
  • Thanks Tim you have answered all my questions! – meda Oct 08 '13 at 21:38