Using FindControl() to find control

Mike Wills picture Mike Wills · Sep 16, 2010 · Viewed 54.7k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 16, 2010

From within the masterpage:

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

From within the view:

litNavLinks.Text = sb.ToString();