Get ID of Master Page object in Content Page - asp.net

If the master page has a label with the id label1 how do I control that id in the content page. The id is not passed down so i can't control it inherently. For example if i have a control with the id contentLabel i can access it code by just typing contentLabel.(whatever i'm doing)

Here are two options:
1: make sure your content aspx specifies MasterType:
   
<%# MasterType VirtualPath="~/yourMasterPageName.master" %>
Doing this lets your content page know what to expect from your master-page and gives you intellisense. So, now you can go ahead and expose the label's Text property on the master page's code-behind.
public string ContentLabelText
{
get { return contentLabel.Text; }
set { contentLabel.Text = value; }
}
Then you can access it in your content page's code-behind page ala:
Master.ContentLabelText = "hah!";
or, 2: You can access the label via FindControl() like so:
var contentLabel = Master.FindControl("contentLabel") as Label;

Related

ASP.NET Can't access user control's property in code-behind file

Visual Studio 2008, C#, ASP.NET
Need to make multiple copies (or instances) of a web user control programmatically.
I have UserControlFile.ascx which contains an asp:Label with ID="vhLabel" in it.
In that file I set label's Text property through public string vhText variable, as usual:
public string vhText
{
set
{
vhLabel.Text = value;
}
}
There are also some divs and other html data in this file that cannot be created in C# programmatically, so I have to use ascx file.
Now, in code-behind file I need to:
clone this user control many times;
set unique value to label's property "Text" of each clone through "vhText" variable.
Please, share your suggestions on these issues. If you need, I can show my code here.
I've been looking for an answer for very long, but still unsuccessful.
You can find a walkthrough of how to programmatically add user controls to your page here: http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx
In your case, you need something like this in your UserControlFile.ascx control (the className attribute is the important bit):
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserControlFile.ascx.cs" Inherits="UserControlFile" className="MyUserControl" %>
<asp:Label ID="vhLabel" runat="server"></asp:Label>
Then, at the top of your page that will include the control (change the file path appropriate to your structure):
<%# Reference Control="~/Controls/UserControlFile.ascx" %>
Finally, the code behind of the page will contain the code to programmatically add the instances of the control via the LoadControl method and the use of the MyUserControl type - defined in the className attribute in the #Control directive above:
protected void Page_Load(object sender, EventArgs e)
{
var control = (ASP.MyUserControl)LoadControl("~/Controls/UserControlFile.ascx");
control.vhText = "1";
Page.Controls.Add(control);
control = (ASP.MyUserControl)LoadControl("~/Controls/UserControlFile.ascx");
control.vhText = "2";
Page.Controls.Add(control);
/* etc... */
}
That should point you in the right direction...
You need to use LoadControl method:
MyUserControl control = (MyUserControl)Page.LoadControl("~/UserControlFile.ascx");
control.vhText = "first control";
Page.Controls.Add(control);
control = (MyUserControl)Page.LoadControl("~/UserControlFile.ascx");
control.vhText = "second control";
Page.Controls.Add(control);
control = (MyUserControl)Page.LoadControl("~/UserControlFile.ascx");
control.vhText = "third control";
Page.Controls.Add(control);

Find Control on MasterPage returns nulll

Im trying to access a ModalPopupExtender control and it allways is returning null or object set not set to an intance of an object. I've tried master.Page.FindControl("") and master.FindControl("") and im still not getting the result
MasterPage master = Page.Master as MasterPage;
AjaxControlToolkit.ModalPopupExtender popup = master.Page.FindControl("ModalPopupExtender2") as AjaxControlToolkit.ModalPopupExtender;
Updated: Cannot change the text of my labels in master page
MasterPage master = Page.Master;
AjaxControlToolkit.ModalPopupExtender popup1 = master.FindControl("ModalPopupExtender1") as AjaxControlToolkit.ModalPopupExtender;
Label lblMessage = master.FindControl("lblMessage") as Label;
lblMessage.Text = msg;
Literal ltrlMessage = master.FindControl("ltrlMessage") as Literal;
ltrlMessage.Text = msg;
Label MessageStatus = master.FindControl("lblMessageStatus") as Label;
MessageStatus.Text = msgStatus;
popup1.Show();
you could do
MasterPage master = Page.Master;
If your page is a child of your master page
try this:
AjaxControlToolkit.ModalPopupExtender popup = (AjaxControlToolkit.ModalPopupExtender)Page.Master.FindControl("ModalPopupExtender2");
Regards
Check out this answer. You can have a strongly typed master page, so you don't have to find and then cast the control. The control on the master would be publicly accessible, and the page would know the type of the master page and have it accessible.
EDIT:
the control is not public
Assuming you've set the Master property in your page directive:
<%# Page MasterPageFile="~/MyMaster.master" ...
Odds are, you probably don't need to actually get to the control. Rather, you need to set something in the master page. I'd just use an internal method to do what you need to do:
public partial class MyMaster: MasterPage
{
internal void SetTheFoo(string foo)
{
this.WhateverControl.Text = foo;
}
//etc...
}
Then, from your page, just call it:
Master.SetTheFoo("Foo");
If you still need to get to the control, then in your master page, you could add a public property exposing your modal popup extender.
public AjaxControlToolkit.ModalPopupExtender MyModalPopup
{
get { return this.TheNonPublicModalPopupExtenderControl; }
}

Can I create custom directives in ASP.NET?

I have created a menu control in asp.net and have put it into master page. This menu control have property ActiveItem which when modified makes one or another item from menu appear as active.
To control active item from child page I have created a control which modifies master page property enforced by IMenuContainer interface to update menu control's active item in master page.
public class MenuActiveItem : Control
{
public ActiveItemEnum ActiveItem
{
get
{
var masterPage = Page.Master as IMenuContainer;
if (masterPage == null)
return ActiveItemEnum.None;
return masterPage.ActiveItem;
}
set
{
var masterPage = Page.Master as IMenuContainer;
if (masterPage == null)
return;
masterPage.ActiveItem = value;
}
}
}
Everything works perfectly and I really enjoy this solution, but I was thinking that, if I knew how, I would have created a custom directive with same feature instead of custom control because it just makes more sense that way.
Does anybody know how to do it?
You should be able to turn this into a custom property of your Page, which you can set in the Page directive.
Create a base class for your page, and then change your Page directives like this:
<%# Page Language="C#" MasterPageFile="~/App.master"
CodeFileBaseClass="BasePage" ActiveItem="myActiveItem" AutoEventWireup="true"
CodeFile="Page1.aspx.cs" Inherits="Page1" %>
You may have to change the property to be a string, and do a conversion to the enum. But otherwise your code can remain the same, and it doesn't have to be in a control.

Can I hide a user control in a master page from a content page?

How can I hide a user control on the master page from a content page? This is code I have on my content page's load.
Dim banner As UserControl = DirectCast(Master.FindControl("uc_banner1"), UserControl)
banner.Visible = True
Does nothing for me :(
Expose the visible property of the user control via a property of the MasterPage.
In your MasterPage:
public bool MyBannerVisibility
{
get { return uc_banner1.Visible; }
set { uc_banner1.Visible = value; }
}
Then make sure to add a reference in your content page:
<%# MasterType TypeName="YourMasterPageTypeName" %>
Then in your content page just do:
Master.MyBannerVisibility = false;
Edit: Since your using VB.net I used a code converter to convert it for you:
Public Property MyBannerVisibility() As String
Get
Return uc_banner1.Visible
End Get
Set
uc_banner1.Visible = value
End Set
End Property
Content Page:
Master.MyBannerVisibility = False

Access a content control in C# when using Master Pages

Good day everyone,
I am building a page in ASP.NET, and using Master Pages in the process.
I have a Content Place Holder name "cphBody" in my Master Page, which will contain the body of each Page for which that Master Page is the Master Page.
In the ASP.NET Web page, I have a Content tag (referencing "cphBody") which also contains some controls (buttons, Infragistics controls, etc.), and I want to access these controls in the CodeBehind file. However, I can't do that directly (this.myControl ...), since they are nested in the Content tag.
I found a workaround with the FindControl method.
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) Master.FindControl("cphBody");
ControlType myControl = (ControlType) contentPlaceHolder.FindControl("ControlName");
That works just fine. However, I am suspecting that it's not a very good design. Do you guys know a more elegant way to do so?
Thank you!
Guillaume Gervais.
I try and avoid FindControl unless there is no alternative, and there's usually a neater way.
How about including the path to your master page at the top of your child page
<%# MasterType VirtualPath="~/MasterPages/PublicUI.Master" %>
Which will allow you to directly call code from your master page code behind.
Then from your master page code behind you could make a property return your control, or make a method on the master page get your control etc.
public Label SomethingLabel
{
get { return lblSomething; }
}
//or
public string SomethingText
{
get { return lblSomething.Text; }
set { lblSomething.Text = value; }
}
Refers to a label on the master page
<asp:Label ID="lblSomething" runat="server" />
Usage:
Master.SomethingLabel.Text = "some text";
//or
Master.SomethingText = "some text";
Rick Strahl has a good explanation (and sample code) here - http://www.west-wind.com/Weblog/posts/5127.aspx
Nothing to do different. Just write this code on child page to access the master page label control.
Label lblMessage = new Label();
lblMessage = (Label)Master.FindControl("lblTest");
lblMessage.Text = DropDownList1.SelectedItem.Text;
I use this code for acess to files recursively:
/// <summary>
/// Recursively iterate through the controls collection to find the child controls of the given control
/// including controls inside child controls. Return all the IDs of controls of the given type
/// </summary>
/// <param name="control"></param>
/// <param name="controlType"></param>
/// <returns></returns>
public static List<string> GetChildControlsId(Control control, Type controlType)
{
List<string> FoundControlsIds = new List<string>();
GetChildControlsIdRecursive(FoundControlsIds, control, controlType);
// return the result as a generic list of Controls
return FoundControlsIds;
}
public static List<string> GetChildControlsIdRecursive(List<string> foundControlsIds, Control control, Type controlType)
{
foreach (Control c in control.Controls)
{
if (controlType == null || controlType.IsAssignableFrom(c.GetType()))
{
// check if the control is already in the collection
String FoundControl = foundControlsIds.Find(delegate(string ctrlId) { return ctrlId == c.ID; });
if (String.IsNullOrEmpty(FoundControl))
{
// add this control and all its nested controls
foundControlsIds.Add(c.ID);
}
}
if (c.HasControls())
{
GetChildControlsIdRecursive(foundControlsIds, c, controlType);
}
}
Hi just thought i'd share my solution, found this works for accessing a 'Control' that is inside an < asp:Panel> which is on a 'ContentPage', but from C# code-behind of the 'MasterPage'. Hope it helps some.
add an < asp:Panel> with an ID="PanelWithLabel" and runat="server" to your ContentPage.
inside the Panel, add an < asp:Label> control with ID="MyLabel".
write (or copy / paste the below) a function in your MasterPage Code-behind as follows: (this accesses the label control, inside the Panel, which are both on the ContentPage, from the Master page code-behind and changes its text to be that of a TextBox on the Master page :)
protected void onButton1_click(object sender, EventArgs e)
{
// find a Panel on Content Page and access its controls (Labels, TextBoxes, etc.) from my master page code behind //
System.Web.UI.WebControls.Panel pnl1;
pnl1 = (System.Web.UI.WebControls.Panel)MainContent.FindControl("PanelWithLabel");
if (pnl1 != null)
{
System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)pnl1.FindControl("MyLabel");
lbl.Text = MyMasterPageTextBox.Text;
}
}

Resources