母版页嵌套子母版页通信

来源:互联网 发布:如何开一家淘宝店铺 编辑:程序博客网 时间:2024/04/28 16:03
vs2005开始就已经有支持母版页了,常常我们在应用的过程当中会需要嵌套多个母版页,因为它实在是好用。

这就出现了母版页嵌套子母版页的状况,那么继承自子母版页的内容页需要与其通信的问题就接踵而至。

举例说明:前提母版页MasterPage.master,子母版页ChildPage.master,含有一GridView控件,继承自MasterPage.master的内容页Index.aspx,继承自ChildPage.master的内容页ContentPage.aspx。

目标:内容页ContentPage.aspx调用ChildPage.master的GridView控件并初始化(内容页与嵌套母版页的通信)。

 

1、母版页MasterPage.master代码:

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

 

2、子母版页ChildPage.master(继承自MasterPage.master)页面代码:

第一句代码<%@ Master Language="C#" AutoEventWireup="true" CodeFile="ChildPage.master.cs" Inherits="ChildPage"  MasterPageFile="~/MasterPage.master" %>

就是对母版页MasterPage.master的继承(即嵌套到母版页MasterPage.master中)

该页中有一个GridView控件,ID为"gv_ChildMenu"

3、继承自子母版页ChildPage.master的内容页Content.aspx页面代码:

[c-sharp] view plaincopyprint?

<%@ Page Language="C#" MasterPageFile="~/ChildPage.master" AutoEventWireup="true" CodeFile="ContentPage.aspx.cs"     Inherits="ContentPage" %>  

  1. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">  
  2. </asp:Content>  

4、内容页content.aspx初始化childPage.master的GridView控件

[c-sharp] view plaincopyprint?
  1. ContentPlaceHolder cont = this.Master.Master.FindControl("ContentPlaceHolderMain"as ContentPlaceHolder;  
  2. GridView dl = cont.FindControl("gv_ChildMenu"as GridView;  
  3. List<ChildMenu> list = new List<ChildMenu>();  
  4. int i = 0;  
  5. while (i <= id)  
  6. {  
  7.     ChildMenu menu = new ChildMenu();  
  8.     menu.ChildMenuName = "菜单"+id+"的子菜单" + i;  
  9.     list.Add(menu);  
  10.     i++;  
  11. }  
  12. dl.DataSource = list;  
  13. dl.DataBind();  

按正常思路:内容页调用母版页应该用这段代码即可


GridView dl = this.Master.FindControl("gv_ChildMenu") as GridView;

就可以得到ChildPage.master的GridView控件对象。

但是ChildPage.master本身是继承自母版页MasterPage.master,所以上述的代码无法得到GridView对象

页必须这样写:

 ContentPlaceHolder cont = this.Master.Master.FindControl("ContentPlaceHolderMain") as ContentPlaceHolder;
        GridView dl = cont.FindControl("gv_ChildMenu") as GridView;

 

先获取Masterpage.master的ContentPlaceHolder对象,然后再通过该对象寻找childPage.master的GridView控

件对象,然后进行初始化。

 

详细源码示例下载地址:http://download.csdn.net/source/2077818

原创粉丝点击