Search code examples
c#asp.netfindcontrol

Using FindControl() to find control


I have a Literal control that I am trying to locate so I can insert text into it. I have a Master page that contains several content placeholders.

<asp:Content ID="Content7" ContentPlaceHolderID="MainLinks" runat="server">
    <h3>Project Navigation</h3>
<ul class="rightColBoxNav">
<asp:Literal ID="litNavLinks" runat="server" />
</ul>
</asp:Content>

I keep getting "Object reference not set to an instance of an object." How do I locate this object so I can find and update it?

I have tried:

((Literal)Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.FindControl("Content7").FindControl("litNavLinks")).Text = sb.ToString();

to no avail. How do I determine the location?


Solution

  • From within the masterpage:

    var literal = (Literal)FindControl("MainLinks").FindControl("litNavLinks");
    literal.Text = sb.ToString();
    

    From within the view:

    litNavLinks.Text = sb.ToString();