Surya sasidhar
Surya sasidhar

Reputation: 30293

Accessing Master Page Controls in Non master page?

In asp.net, how can I access the master page controls in a non-master page?

Upvotes: 3

Views: 9133

Answers (3)

Mubarek
Mubarek

Reputation: 2689

Use can

TextBox txt1 = (TextBox)this.Master.FindControl("MytxtBox");
txt1.Text="Content Changed from content page";

Upvotes: 2

Ravi Gadag
Ravi Gadag

Reputation: 15851

add this in your webPage to access the contents of master page Master Page : programatically access

<%@ MasterType virtualpath="Your MasterPath" %>

you can do like this (alternative way )

MasterPage mstr 
Label lbl
mstr = Page.Master
If (mstr.ID == "yourMasterIDString")
{
     lbl = mstr.FindControl("lblBar")
        If (lbl !=null)
          {
                lbl.Text = "Do some Logic"
          }
}

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39888

You can access the Masterpage as a property on your current page. However, the controls on your master page are protected so you can't access them directly. But you can access them by using FindControl(string name). The code you need to use depends on if the control is inside or outside a content place holder.

// Gets a reference to a TextBox control inside a ContentPlaceHolder
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder = 
    (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
    mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
    if(mpTextBox != null)
    {
        mpTextBox.Text = "TextBox found!";
    }
}

// Gets a reference to a Label control that is not in a 
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
    Label1.Text = "Master page label = " + mpLabel.Text;
}

Upvotes: 5

Related Questions