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>
Have you tried to first find the parent container of the user control (e.g. #ParentContainer) and then use FindControl on this object to find the desired user control?
See: Find a control on a page with a master page
Like this:
The best approach is to provide a property in your
MasterPage
with a meaningful name and typestring
. This property gets/sets the text of the label in theUserControl
.In order to meet this objective provide also a property in your
UserControl
with the same meaningful name and typestring
. This property gets/sets the text of the label.You have to cast
this.Master
to the actual type of yourMasterPage
which isMaster1
. Then you can access this custom property.So here is your
UserControl
:This is your
MasterPage
and this is your page:
Ok after some research i have found he answer:
First i have find that user control like below:
After this i am finding my label from this user control like this: