有以下两个页面default.aspx和result.aspx,代码如下:
<!-- default.aspx -->
<%@ page language="c#" autoeventwireup="true" masterpagefile="~/default.master" codefile="default.aspx.cs" inherits="_default" %>
<asp:content id="content1" runat="server" contentplaceholderid="contentplaceholder1">
<asp:label id="label1" runat="server" text="please input a string here"></asp:label>
<asp:textbox id="textbox1" runat="server"></asp:textbox>
<asp:button id="button1" runat="server" text="button" postbackurl="~/result.aspx" /></asp:content>
//default.aspx.cs
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
//using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
}
}
<!-- result.aspx -->
<%@ page language="c#" masterpagefile="~/default.master" autoeventwireup="true" codefile="result.aspx.cs" inherits="result" title="untitled page" %>
<asp:content id="content1" contentplaceholderid="contentplaceholder1" runat="server">
<asp:label id="label1" runat="server" text="the string you input in the previous page is"></asp:label>
<asp:textbox id="textbox1" runat="server"></asp:textbox>
</asp:content>
//result.aspx.cs
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
public partial class result : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
if (previouspage != null)
{
textbox tb = (textbox)previouspage.findcontrol("textbox1");
if (tb != null)
textbox1.text = tb.text;
}
}
}
这两个页面都指定了masterpagefile属性。因为该masterpage中的内容无关紧要,就不列出来了。在default.aspx上有两个控件:textbox1用于接受用户的输入,button1用于提交页面,其postbackurl指向result.aspx。在result.aspx.cs的page_load方法中尝试在textbox1中显示用户在前一页面的textbox1中输入的字符串。当执行以下语句时:
textbox tb = (textbox)previouspage.findcontrol("textbox1");
tb的值为null。将以上语句更改为如下代码:
content con = (content)previouspage.findcontrol("content1");
if (con == null)
return;
textbox tb = (textbox)con.findcontrol("textbox1");
但con的值为null,这样后续的语句也不可能执行了。问题出在哪里呢?
经过一番搜索,在forums.asp.net中找到了答案,以下引用的是bitmask的说法:
...becasue the content controls themselves dissapear after the master page rearranges the page. you can use the contentplaceholders, or the <form> on the masterpage if there are no inamingcontainers between the form and the control you need.
所以以上的代码应该改成:
textbox tb = (textbox)previouspage.master.findcontrol("contentplaceholder1").findcontrol("textbox1");
bitmask还在他的博客上写了一篇文章来阐述findcontrol方法和inamingcontainers接口:
http://www.odetocode.com/articles/116.aspx
http://movingboy.cnblogs.com/archive/2006/07/06/444690.html
文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




