I've found threads solving this issue within Default.aspx and Default.aspx.cs, but applying those solutions to my problem don't fix my issue. None of them are helpful in this context:
I'm trying to access an element on my Site.master page within Default.aspx.cs. I want to hide this element if a certain condition isn't met. However, I cannot reference any elements within my Site.master page (either within Default.aspx.cs OR Site.master.cs)
Code:
Site.master:
<li><a runat="server" id="editLink" href="~/Edit">Edit</a></li>
Default.aspx.cs:
MasterPage master = this.Master;
Control linkControl = master.FindControl("editLink");
linkControl.Visible = false;
I've also tried:
Site.master:
<asp:Panel ID="Panel1" runat="server">
<li><a runat="server" id="editLink" href="~/Edit">Edit</a></li>
</asp:Panel>
Default.aspx.cs:
((Panel)Master.FindControl("Panel1")).Visible = false;
//or..
//Panel testPanel = ((Panel)Master.FindControl("Panel1"));
//Panel1.Visible = false;
I don't know where to start. Thanks!
EDIT:
I've tried to apply resolutions from:
ASP.NET - Accessing Master Page elements form the Content Page
What is a NullReferenceException, and how do I fix it?
Specifically from the first:
adding the following to Default.aspx
<%@ MasterType virtualpath="~/Site.master" %>
adding the following to Default.aspx.cs
Panel testPanel = (Panel)Master.FindControl("Panel1");
testPanel.Visible = true;
The above code is the suggested fix for the first thread, but I get the same error. The second thread seemed to suggest I was referencing the element before it was created thus returning the nullreferenceexception error, but I do not believe this is the case. Ultimately, I do not understand enough to utilize those threads.
EDIT
Site.master MCVE:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %>
<form id="wrapForm" runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
<asp:Panel ID="Panel1" runat="server">Test Text</asp:Panel>
</asp:ContentPlaceHolder>
</form>
Default.aspx.cs MCVE:
protected void Page_Load(object sender, EventArgs e)
{
Panel testPanel = (Panel)Master.FindControl("Panel1");
testPanel.Visible = true;
}