加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在页面中查找控件

发布时间:2020-12-15 03:43:08 所属栏目:百科 来源:网络整理
导读:HTML body form id="form1" runat="server" asp:Button runat="server" ID="a" OnClick="a_Click" Text="apd"/ /form/body 码 protected void a_Click(object sender,EventArgs e){ Response.Write(((Button)FindControl("a")).Text);} 此代码工作正常. 但是
HTML
<body>
    <form id="form1" runat="server">    
       <asp:Button runat="server" ID="a" OnClick="a_Click" Text="apd"/>    
    </form>
</body>

protected  void a_Click(object sender,EventArgs e)
{
    Response.Write(((Button)FindControl("a")).Text);

}

此代码工作正常.

但是,这段代码:

HTML

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


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button runat="server" ID="a" OnClick="a_Click" Text="andj"/>
</asp:Content>

protected void a_Click(object sender,EventArgs e)
{
    Response.Write(((Button)FindControl("a")).Text);
}

此代码不工作,FindControl返回Null – 为什么会这样?

FindControl方法在一个简单的页面工作正常,但在母版页,它不起作用?

a的ID被更改为ctl00_ContentPlaceHolder1_a – 如何找到控件?

解决方法

要在内容页面上找到按钮,您必须首先搜索ContentPlaceHolder1控件.
然后使用ContentPlaceHolder1控件上的FindControl功能搜索您的按钮:
ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
 Response.Write(((Button)cph.FindControl("a")).Text);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读