FindControl用于在使用母版页的页面上查找控件

时间:2015-05-04 07:53:27

标签: c# asp.net master-pages findcontrol

我有使用母版页的aspx

<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="server">
   <div class="mlists">
       <a href="?"><img id="i1" src="../img/1.png" runat="server" alt="1"/></a>
       <a href="?"><img id="i2" src="../img/2.png" runat="server" alt="2"/></a> 
       <a href="?"><img id="i3" src="../img/3.png" runat="server" alt="3"/></a> 

   </div>
</asp:Content>

但我无法使用此代码访问图像控件:

var control = FindControl("Content1").FindControl("i2");
((HtmlImage)control).Src = "../img/x.png";

  

对象引用未设置为对象的实例。

发生

错误,因为FindControl("Content1")返回null。请注意,此代码也返回null

var control = FindControl("i2");

2 个答案:

答案 0 :(得分:0)

       // Get a reference to the master page
        MasterPage ctl00 = FindControl("ctl00") as MasterPage;

        // Get a reference to the ContentPlaceHolder
        ContentPlaceHolder mainContent = ctl00.FindControl("MainContent") as ContentPlaceHolder;

           // Get a reference to the Repeater
       Repeater repeater = mainContent.FindControl("Repeater1") as Repeater;

  This is how i get to a repeater control in a working application.
Follow this pattern you can get anything in your master page and even content page

答案 1 :(得分:0)

您无法访问内容,请参阅this question

也许,您想将“runat = server”添加到div并访问ImageControls。

<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="content">
    <div class="mlists" runat="server" id="div">
       <a href="?"><img id="i1" src="../img/1.png" runat="server" alt="1"/></a>
       <a href="?"><img id="i2" src="../img/2.png" runat="server" alt="2"/></a> 
       <a href="?"><img id="i3" src="../img/3.png" runat="server" alt="3"/></a> 

   </div>
</asp:Content>

然后访问代码中的控件,如下所示:

var control = div.FindControl("i2");
((HtmlImage)control).Src = "../img/x.png";