asp.net findcontrol html控件,如何使用findcontrol查找内容页上的某个控件?_asp.net技巧...

有以下两个页面Default.aspx和Result.aspx,代码如下:

//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.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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值