Make control public in designer generated file - asp.net

It there any way to tell the ASP.NET .designer.cs code generator to create public controls instead of protected?
.master.designer.cs file:
/// <summary>
/// btnLanguageEN control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnLanguageEN;
.master file:
<asp:LinkButton runat="server" ID="btnLanguageEN" OnClick="btnLanguageEN_Click" Text="ENG" />
Why I need it? I am trying to access to master page controls from child page:
.aspx file:
<%# MasterType TypeName="www.MainMaster" %>
.aspx.cs file:
Master.btnLanguageEN.Text = "123";
Here I receive an error stating that btnLanguageEN is protected.

Rather than modify the designer generated code, reference the control through the Page's Master property using the FindControl method.
You'll need to add the following directive to the top of your child page (if it's not already there) to reference the master page:
<%# MasterType virtualpath="~/Masters/Master1.master" %>
Then, in your child page's code behind, you can do things like the following.
void Page_Load()
{
// Gets a reference to a LinkButton on the master mage.
// a ContentPlaceHolder
LinkButton mpLinkButton = (LinkButton) Master.FindControl("btnLanguageEN");
if(mpLinkButton != null)
{
mpLinkButton.Text = "123 - Labelled by Child Page";
}
}
Reference: http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx

Create a strongly typed reference to your master page by including this on your ASPX page.
<%# MasterType virtualpath="~/Masters/Master1.master" %>
On your Master Page, create a property. This will make the control available from other classes..
public Button btnLanguageENMaster
{
get {return btnLanguageEN;}
private set;
}
Then from your regular page code behind you can do this...
Master.btnLanguageENMaster.Text = "Hello, world!"

Related

Master property is not auto generated in aspx designer causing runtime errors

I have a content page that uses a MasterPageFile, and in the code we try to access a master property Master.SessionId.
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminFrontend.Master" AutoEventWireup="true"
CodeBehind="Reasons.aspx.cs" Inherits="Admin.Other.Reasons" %>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMainBody" runat="server">
<reason session-id="<%=Master.SessionId%>">
</reason>
</asp:Content>
But the Master.SessionId is not recognized, Master is not referring to the correct master file. Similar code works on another file within the project. The only notable difference that we found is that the page that works has the following auto-generated code in the aspx.designer.cs file.
public partial class MyChart {
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new Admin.AdminFrontend Master {
get {
return ((Admin.AdminFrontend)(base.Master));
}
}
}
This is the designer for my Reasons.aspx file.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Admin.Other
{
public partial class Reasons
{
}
}
I am not sure what is the problem, why in one file that property is auto-generated and not in the other. I thought Visual Studio is doing something crazy. I restarted VS2019 and also tried restarting my machine. Both didn't solve the
problem.
There may not even 'be' a Designer page for the "Reasons.aspx.cs". Please check to ensure it exists for the Reasons.aspx page (open the Solution Explorer and view the associated to the Reason.aspx file). If the Designer file does not exist, select/highlight the Reason.aspx file in the Solution Explorer, then use the upper menu bar (in Visual Studio), and choose the Project > Convert to Web Application selection. If that selection is missing from the Projects pulldown menu, this typically indicates all Designer files are connected to your CodeBehind files.
If you do have a Reasons.aspx.designer.cs, please provide the code here so we can compare it to the one from your MyChart example.
At your Reasons.aspx.cs file,
you can add public property and return the Master.sessionID.
For example;
public partial class MyChart
{
public string MySession
{
get
{
return Master.SessionID;
}
}
}
At your aspx file, use
<reason session-id="<%=MySession%>"></reason>

Web site to Web App: aspx.cs can't see controls in .aspx

I am trying to convert a web site project to a web app and I'm running into some issues where the .aspx.cs files can't see any controls in the .aspx. I've tried deleting the .designer.cs files and converting to a web app again but that hasn't fixed my problems. If I change the namespace of the .designer.cs files to 'SoftwareCheckout,' (the same namespace as my .aspx.cs) the .aspx.cs can see the controls in the .aspx fine, but since the .designer.cs is auto-generated, I will loose any changes to it as soon as it's regenerated. This leads me to believe it is a problem with my namespaces but I'm not 100% sure.
Here is the top line of my .aspx called StuCheckout.aspx:
<%# Page Language="C#" AutoEventWireup="True" Inherits="StuCheckout" Codebehind="StuCheckout.aspx.cs" %>
Here's the first couple lines of my .aspx.cs called StuCheckout.aspx.cs (lblUser and lblTime can't be accessed for example)
namespace SoftwareCheckout
{
public partial class StuCheckout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblUser.Text = CurrentUser.getUsername();
lblTime.Text = CurrentUser.getDate();
setLocalRestrictions();
if (!(lblErrorText.Text == String.Empty))
lblErrorText.Visible = true;
My .designer.cs looks like this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class StuCheckout {
/// <summary>
/// Head1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
Has anyone else ran into this issue? I'm running out of ideas here, any help is greatly appreciated!
Try adding the namespace to the Inherits and Class declarations on your front-side (.aspx) pages; the #Page directive has an Inherits or Class attribute you can use.
See "Additional Conversion Options" section here:
http://msdn.microsoft.com/en-us/library/aa983476(v=vs.100).aspx

ASP.Net Calling Site.Master method from web page not working

I saw on several web pages how to interface to a public method defined in a master file from a web page call behind code that uses that master file.
(I am using ASP.Net 4.0 on Visual Studio 2012.)
The procedure is (copied from article):
Make sure the function is accessible to the page (i.e. declared
public), and use the MasterType declaration in the ContentPage:
<%# Page .... %>
<%# MasterType VirtualPath="~/masterpage.master" %>
In the page, use Page.Master.MyFunction() to access the function.
*Note: before being able to access the function, you'll need to save & build.
The problem is that I do not see the method. Here is what I have:
Web Page (stored in /MyFolder, so /MyFolder):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Logout.aspx.cs" Inherits="BvCorpMain.Candidates.Logout" %>
<%# MasterType VirtualPath="/SiteMasters/Site.Master" %>
Site.Master CS file (stored in /SiteMasters folder):
public void UpdateUserBlocksToCookie()
{
}
When I go into the code behind for the logout page and in a method I type in "Page.Master.", I do not see my method.
Your page is inheriting from System.Web.UI.Page, which only knows that its master page is of type System.Web.UI.MasterPage. If you are making modifications to a child class of MasterPage, then you need to cast the Page.Master property to your child class.
public class MyPage : System.Web.UI.Page
{
public new MyMaster Master { get { return base.Master as MyMaster; } }
public void Page_Load(object sender, EventArgs e)
{
Master.MyMasterPageFunction();
}
}
public class MyMaster : System.Web.UI.MasterPage
{
public void MyMasterPageFunction()
{
}
}
The previous answer did educate me, however I believe the resolution was to restart VS2012, maybe cleaning the solution and rebuilding did not hurt. Either way.
Microsoft adds in the following code automatically to the .aspx.designer.cs file.
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new MyNamespace.Site Master {
get {
return ((BvCorpMain.Site)(base.Master));
}
The previous answer conflicts with this definition. Also, the previous answer of MyMaster, although granting access does not give (automatically at least) to needed form information. I checked. Using the existing master file is the cleanest.
The definition for the master.cs file is:
namespace MyNamespace
{
public partial class Site : System.Web.UI.MasterPage
As you can see, Microsoft did give access to MyNamespace.Site, which is what I needed, with "Master.".
I did not think to check the .aspx.designer.cs file for that definition, when I was having the problems. Possibly the definition was lacking and got added later, when either I rebuilt or did a save, which I had previously done, or whatever.
Knowing the addition does simplify things, as I can add that in manually if it does not exist using that construct.

Asp.net: Can we use MasterPage's viewstate in ContentPage?

Asp.net: Can we use MasterPage's viewstate in ContentPage ?
From a Content Page you can refer to a MasterPage through the Master Property. Create a Property on the Master Page that uses its getter and setter to store its value in ViewState, like so:
string MyProperty
{
get { return ViewState["MyProperty"] as string; }
set { ViewState["MyProperty"] = value; }
}
Obviously you could make that code safer by testing for nulls and what-not...
Here's the important bit: Viewstate elements are only accessible from the controls that added them so you need to refer back up the tree.
You can also strongly type the Master property on Page by using the <%# MasterType %> directive in your ASPX file, thusly:
<%# MasterType VirtualPath="~/masters/SourcePage.master"" %>
HTH.

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