简体   繁体   中英

Null Reference Literal Control

I am trying to pass text to a Literal, the parent.master has the ContentTemplateID's and the Child.master has the contentID's, one of them is the literal of form

<asp:Literal runat="server" ID="myLiteral"></Literal>

I am trying to pass it from a UserControl.cs file like this

 gooleTrackin = track.GetTrack(track.OrderType.YAHOO); 
 Literal mpLiteral = (Literal)this.Parent.Page.Master.FindControl("myLiteral");
mpLiteral.Text = gooleTrackin.ToString(); //nullReference here 

But it is giving me NulLReference in the last line.

By the way I do not have access to the.cs files of the master pages, it has to be done through the UserControl.

Thank you

ADDITIONAL CODE (THIS IS LOCATED IN THE CHILD.MASTER)

<%@ Master Language="C#" AutoEventWireup="true" MasterPageFile="../common/child.master" %>
<%@ Register Src="UserControl.ascx" TagName="UserControl" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
   <div class="inner"><uc1:UserControl ID="theRceipt" runat="server" Visible="true"/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="BottomContentTemplate" Runat="Server">
<div style="margin-bottom:30px;">
   <asp:Literal ID="myLiteral" runat="server"></asp:Literal>
<a href="~/" id="23" runat="server" class="BackLink">Back to Home Page</a>
</div>
</asp:Content>

When master page is used, controls from master page are merged into the control hierarchy of page so this can be an issue while finding controls. I will suggest that you try following and see if it works:

Literal mpLiteral = (Literal)this.Page.FindControl("myLiteral");

OR

Literal mpLiteral = (Literal)this.Parent.FindControl("myLiteral");

Otherwise, you may have to try recursive find - see http://www.west-wind.com/weblog/posts/2006/Apr/09/ASPNET-20-MasterPages-and-FindControl

However, I will rather recommend a alternate way - assuming that you have defined your literal control in Child.Master and Child is the name of code behind class for master, you can add an helper method in it such as

public void UpdateMyLiteral(string text)
{
   myLiteral.Text = text;
}

And in user control code, invoke the helper method such as

((Child)this.Page.Master).UpdateMyLiteral("xyz");

Note that we are casting master to its code-behind class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM