0

I have this aspx that uses a master page:

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

but I can't access to image controls using this code:

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

and

Object reference not set to an instance of an object.

error occurs, since FindControl("Content1") returns null. note that also this code returns null:

var control = FindControl("i2");
Majid
  • 13,853
  • 15
  • 77
  • 113

2 Answers2

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
0

You can't access content, please refer to this question.

Perhaps, you wanted to add "runat=server" to div and access 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>

Then access controls in code behind like this:

var control = div.FindControl("i2");
((HtmlImage)control).Src = "../img/x.png";
Community
  • 1
  • 1
tynar
  • 136
  • 8