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?
The FindControl method can be used to access a control whose ID is not available at design time. The method searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page.
To reference a control on the master page Because the TextBox control is inside a ContentPlaceHolder control, you must first get a reference to the ContentPlaceHolder and then use its FindControl method to locate the TextBox control.
The identifier for the control to be found. The specified control, or null if the specified control does not exist. The following example defines a Button1_Click event handler. When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page.
Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method. Searches the current naming container for a server control with the specified id parameter.
When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page. If the control is found, its parent is determined using the Parent property and the parent control's ID is written to the page. If TextBox2 is not found, "Control Not Found" is written to the page.
From within the masterpage:
var literal = (Literal)FindControl("MainLinks").FindControl("litNavLinks");
literal.Text = sb.ToString();
From within the view:
litNavLinks.Text = sb.ToString();
I would try a different approach.
How about using a user control and exposing the relevant properties to get or set the text value.
The property would be accessing the literal control. However, the page calling the property wouldn't be any wiser.
Remember we live in a OO world.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With