简体   繁体   中英

accessing a user control from masterpage

I have a user control in my master page under the login view under the Role groups.Here is the control.Its not in the content placeholder.However if i try to access it i get null result.How can i access this from my page code behind.I am having problem getting it from master page.

<asp:RoleGroup Roles="Students">
                    <ContentTemplate>
                        <uc1:studentsPanel runat="server" ID="studentcontrol" />
                    </ContentTemplate>
                     </asp:RoleGroup>

Here is how i am having my code

LoginView control = Page.Master.FindControl("studentcontrol") as LoginView;
            if (control != null)
            {
                Label1.Text = "found";

            }

Here's the code I use to get to controls in MasterPages

    //Master page from user control
    LoginControl control

    Page page = (Page)this.Page;
    MasterPage master = (MasterPage)page.Master;

    control= (LoginControl )master.FindControl("studentcontrol");

    if (control!= null)
    {
        Label1.Text = "found";
    }

We can't see the whole code, but your snippets seem correct. Try first not to cast your control to LoginView - the reason might be that your panel is not of that type. To try out if the control is found at all, use

if(Page.Master.FindControl("studentcontrol") != null) {
    Label1.Text = "found";
}

first before adding another possible source of failure.

There's two more explicit answers that don't need to be repeated here. You find wonderful explanations here and here .

as @Krishnraj said,

i dont know which is control within studentsPanel UserControl, but i assume that Label. You should access like that,

var Loginview = (Master.FindControl("LoginView1") as LoginView);
Control cont = new Control();
Loginview.RoleGroups[0].ContentTemplate.InstantiateIn(cont);
(cont.Controls[1].FindControl("_trylbl") as Label).Text = "Hello say";

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