NullReferenceException异常是在母版页用户code未处理 [英] nullreferenceexception was unhandled by user code in Master Page
问题描述
我有主page.Below是设计师的部分。
I am having master page.Below is the Designer part.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
<asp:Label ID="lblMaster" runat="server" Text=""></asp:Label>
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
在母版页的Page_Load中,我写的
lblMaster.Text =大师;
In page_load of Master Page ,I write lblMaster.Text = "Master";
在我的Asp.Net页,
In my Asp.Net page,
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MasterPractice.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Label ID="lblfrm" runat="server" Text="Label"></asp:Label>
</asp:Content>
在我的Page_Load我得到的,
In my page_load I get,
lblfrm.Text = "Form";
我收到提到的错误在我的母版页。
I am getting the mentioned error at my master page.
请指引我要提到的担忧。
Please guide me for mentioned concerns.
推荐答案
由于该标签
是在的ContentPlaceHolder
控制,你首先必须获得的的ContentPlaceHolder
的引用,然后使用它的的FindControl
的方法来找到标签
。
Because the Label
is inside a ContentPlaceHolder
control, you must first get a reference to the ContentPlaceHolder
and then use its FindControl
method to locate the Label
.
ContentPlaceHolder Content2;
Label lblfrm;
Content2 = (ContentPlaceHolder)Master.FindControl("Content2");
if(Content2 != null)
{
lblfrm = (Label) Content2.FindControl("lblfrm");
if(lblfrm != null)
{
lblfrm.Text = "Form";
}
}
修改:要找到 lblMaster
的要求,在注释:
Edit: To find lblMaster
as requested in comment:
ContentPlaceHolder ContentPlaceHolder1;
Label lblMaster;
ContentPlaceHolder1 = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(ContentPlaceHolder1 != null)
{
lblMaster = (Label) ContentPlaceHolder1.FindControl("lblMaster");
if(lblMaster != null)
{
lblMaster.Text = "Master";
}
}
这篇关于NullReferenceException异常是在母版页用户code未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!