首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

master.FindControl的有关问题,初学者!

2013-01-04 
master.FindControl的问题,菜鸟求助!!我创建了一个网站,里面一个母版页,一个内容页,现在我在母版页添加了

master.FindControl的问题,菜鸟求助!!
我创建了一个网站,里面一个母版页,一个内容页,现在我在母版页添加了一个label,显示系统时间,在内容页中也添加一个label,用于显示母版页label的文本,但是抛出了异常。具体如下:
母版页:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MainMaster.master.cs" Inherits="MainMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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="lbM" runat="server"></asp:Label>
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MainMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lbM.Text = "今天是" + DateTime.Today.Year + "年" + DateTime.Today.Month + "月" + DateTime.Today.Day + "日";
    }
}

内容页:

<%@ Page Title="" Language="C#" MasterPageFile="~/MainMaster.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
    <asp:Label ID="lbD" runat="server" Text="Label"></asp:Label>
</p>
</asp:Content>

cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        [color=#FF0000]Label lb = (Label)this.Master.FindControl("lbM");
        lbD.Text = lb.Text;
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

抛出异常:

lbM.Text = "今天是" + DateTime.Today.Year + "年" + DateTime.Today.Month + "月" + DateTime.Today.Day + "日";---未将对象引用设置到对象的实例

求解!!
[解决办法]
ContentPlaceHolder是用来放内容页的内容的,在母板页中不需要添加ContentPlaceHolder的内容



<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:Label ID="lbM" runat="server"></asp:Label>

这样内容页就能显示Label的内容了
[解决办法]
ContentPlaceHolder是用来放内容页的内容的,ContentPlaceHolder 控件在母版页中定义相对内容区域,并呈现在内容页中找到的相关的 Content  控件的所有文本、标记和服务器控件。

右键查看HTML即可知道的
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
            <asp:Label ID="lbM" runat="server"></asp:Label>
        </asp:ContentPlaceHolder>
这里面是不产生的。

热点排行