Search code examples
c#asp.netuser-controlsmaster-pagesfindcontrol

How to find label control from content page which is inside master page of user control?


I have one page:Abc.aspx

On this Abc.aspx page i have used one master page that is Master1.Master.

Now on this master page i have rendered 1 usercontrol name as Usercontrol1.ascx.

On this User control i have put 1 label named as lbl1.

 <asp:Label runat="server" ID="lbl1"></asp:Label>

So now on page load event of Abc.aspx page i want to find this control and i have tried but getting null:

 protected void Page_Load(object sender, EventArgs e)
        {
            var lbl = ((Label)this.Master.FindControl("lbl1")); // null here
            ((Label)this.Page.Master.FindControl("lbl1")).Text = "Hello"; //error here:object reference not set to instance of object
        }

This is my master page:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Master1.Master.cs" Inherits="" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>

<body>
    <form runat="server">
   <div id="Load">
                    <uc2:UserControl1 ID="UserControl1 " runat="server" />
                    <asp:ContentPlaceHolder ID="cphMain" runat="server">
                    </asp:ContentPlaceHolder>
                </div>
 </form>
</body>
</html>

Solution

  • The best approach is to provide a property in your MasterPage with a meaningful name and type string. This property gets/sets the text of the label in the UserControl.

    In order to meet this objective provide also a property in your UserControl with the same meaningful name and type string. This property gets/sets the text of the label.

    You have to cast this.Master to the actual type of your MasterPage which is Master1. Then you can access this custom property.

    So here is your UserControl:

    public partial class UserControl1 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public string MeaningfulNameForLabelText
        {
            get { return this.lbl1.Text; }
            set { this.lbl1.Text = value; }
        } 
    }
    

    This is your MasterPage

    public partial class Master1 : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public string MeaningfulNameForLabelText
        {
            get { return this.UserControl1.MeaningfulNameForLabelText; }
            set { this.UserControl1.MeaningfulNameForLabelText = value; }
        } 
    }
    

    and this is your page:

    protected void Page_Load(object sender, EventArgs e)
    {
        var master = this.Master as Master1;
        if (master != null)
        {
            master.MeaningfulNameForLabelText = "Hello";
        }
    }