简体   繁体   中英

Problem with setting visibility of controls in child master page in asp.net

I have a parent master page (Master.Master) and child master page (Child.Master). The Child.Master inherits Master.Master master page file. Now in the Child.Master i want to set the visibility of Div (whose ID is Div1) to false, for which i'm using the following code:

protected void Page_Load(object sender, EventArgs e)
{
   this.FindControl("Div1").Visible = false;
}

Here is the code in the Child Master Page file:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Webstore.Master.cs" Inherits="WebStore.WebStoreMaster" MasterPageFile="~/Login.Master" %>
<asp:Content ID="UserMaster" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">    
<div id="Div1" runat="server">
<div id="Sidebar" runat="server" style="float: left; margin-top: 100px; margin-right: 20px;">
</div>
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>

</asp:Content>

The compiler is giving me the following error:

Object reference not set to an instance of an object.

Can someone explain why is it happening so??

Thanks in anticipation

EDIT:

In this case, if the div is a top level element, and you are in the page_load of the child master page in which the div resides, you should just be able to do

Div1.Visible = false;

Why not use a Panel control?

you should say

this.Master.FindControl("Div1").Visible = false;

Master page is loaded is after page_load. Therefore when you attempt to address the master page during page_load it's properties and methods are not yet available. Move this down in the page life cycle. ASP.NET Page Life cycle , Another SO answer on Masterpage/page life cycle . the child master is loaded during the page_load, and parent master is loaded during the child master page_load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM