S Nash
S Nash

Reputation: 2509

Cannot access a control in master page

In Master page I have:

 <a id="loginlink" href="Login.aspx">Login</a>
  <a id="logoutlink" href="Login.aspx">Logout</a>

In other page which uses this master page I try this:

  Page.Master.FindControl("loginlink").Visible = false;

This is similar code provided in a Microsoft page. But I get:

An exception of type 'System.NullReferenceException' occurred in HousingSurvey.dll but was not handled in user code

Upvotes: 1

Views: 85

Answers (2)

mason
mason

Reputation: 32719

Strong typing here would be better. That way if the name of the control changes, you'll get a compilation error rather than runtime. Fail early.

Master Page

<a id="loginlink" href="Login.aspx" runat="server">Login</a>
<a id="logoutlink" href="Login.aspx" runat="server">Logout</a>

Content Page

<%@ MasterType VirtualPath="~/masters/SourcePage.master" %>

Code behind

Master.loginlink.Visible = false;

Upvotes: 0

Andrei
Andrei

Reputation: 56716

These are not controls yet, just a markup. To make them server-side controls, add runat="server":

<a id="loginlink" href="Login.aspx" runat="server">Login</a>
<a id="logoutlink" href="Login.aspx" runat="server">Logout</a>

Upvotes: 2

Related Questions