ASP.NET how to access public properties? - asp.net

I have two pages page1.aspx and page2.aspx, both have code behind with partial classes.
How do i access public property message on page1.aspx from page2.aspx ?
public string message { get; set; }

Update
I just read that the one is MasterPage and the other is the client to masterpage ?
then its diferent way.
Page to Page
If you have 2 simple diferent pages.
I have done it this way.
Its a post value, by using asp.net tricks :)
On Page2.aspx add this on top.
<%# PreviousPageType VirtualPath="Page1.aspx" %>
and how I read from Page1.aspx on code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Page.PreviousPage != null)
{
if(Page.PreviousPage.IsCrossPagePostBack == true)
{
txtGetItFromPreviusPage.Text = PreviousPage.SomeString;
}
}
}
}
On Page1.aspx
the button that send me to Page2.aspx
<asp:Button ID="btnEna" runat="server" Text="Send Some variables to other page"
PostBackUrl="Page2.aspx"
onclick="btnMoveSelection_Click" />
and the code that I use for Page1 calculations or other thinks
public string SomeString
{
set
{
ViewState["txtSomeString"] = value;
}
get
{
if (ViewState["txtSomeString"] != null)
return ViewState["txtSomeString"].ToString();
else
return string.Empty;
}
}
protected void btnMoveSelection_Click(object sender, EventArgs e)
{
// some final calculations
}

If the one is the Master page, and the other is the page that use the master.
The Master Page
<body>
<form id="form1" runat="server">
<div>
<asp:Literal runat="server" ID="txtOnMaster"></asp:Literal>
<br />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
and the code behind
public partial class Dokimes_StackOverFlow_MasterPage : System.Web.UI.MasterPage
{
public string TextToMaster
{
get { return txtOnMaster.Text; }
set { txtOnMaster.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// here I find the control in the client page
Control FindMe = ContentPlaceHolder1.FindControl("txtOut");
// and if exist I set the text to client from the master
if (FindMe != null)
{
((Literal)FindMe).Text = "Get from Master Page";
}
}
}
and now the Page1.aspx that have the previus master page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Literal runat="server" ID="txtOut"></asp:Literal>
</asp:Content>
and the code
protected void Page_Load(object sender, EventArgs e)
{
// here I set the text on master page from client
((Dokimes_StackOverFlow_MasterPage)Master).TextToMaster = "Set from Client";
}

If you are NOT in a sessionless environment, then in the transmitter page, push your string (or your object - e.g., a Dictionary ) into session:
Session("MyVar") = "WhatEver"
In the receiver page, you can get it back with:
MyPreviousVar = Session("MyVar")

If you want a message property on every page. You could implement your own BasePage and define the message property in your base page. Then derive subsequent pages from your custom base page. That way all of your pages will always have a message property.
However, this isn't going to keep the message property constant through out each page. If you are trying to pass values between pages then you should use either session state or a querystring
This MSDN page may be of use to you.

You shouldn't really be doing this, pages should be standalone entities. If you need to pass this data from one form to another, consider using the querystring, or posting your form to the second page.
OK. Have you tried then Page.Master.Property?

Related

How to access content page control from master page in asp.net c#?

I have a literal Control in my default.aspx, and i want to access this from my masterpage.When i try to do this,i got null exception error(object reference missing).
You can use FindControl in your master page.
Content page:
<asp:Literal runat="server" ID="myLiteral"></asp:Literal>
And in your master page load (or other place):
protected void Page_Load(object sender, EventArgs e) {
var myLiteral = ContentPlaceHolder1.FindControl("myLiteral");
if (myLiteral != null) {
((Literal)myLiteral).Text = "Hello World!";
}
}
Where ContentPlaceHolder1 is the ID of your placeholder in the master page.

how to update master page in all child pages without refreshing

As i am new to asp.net i need some help from you,
i am using a MasterPage and child pages.
In master page I have a Label in which it shows the items added to cart.
when i am adding a product in products page.aspx it is updated in master page as (1 item) and showing in the label but when i am coming to homepage.aspx it is not showing i am using same master page in home.aspx.
If i refresh the home.aspx, it is updated. I need to update it without refreshing.
Sample code look like this
MasterPage markup: Here's the label in your masterpage which you want to be update from childpage
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
MasterPage.cs:
public partial class MasterPage : System.Web.UI.MasterPage
{
public string labeltext
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
ChildPage.cs:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.labeltext = "Your value"; // set your value
}

Set value to TextBox in UserControl inside placeholder

I have an textbox inside an user control. I created dinamically this user control and load in placeholder.
But when I tried to assign a value to the textbox, I raised next below error:
Object reference not set to an instance of an object
This is the user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>
The access modifier is (In the user control):
public string TxtFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
In the web form I have the control reference:
<%# Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx" %>
In the code behind of the user control is:
public partial class frm_VerifyIdentity : System.Web.UI.Page
{
IVT_FormClient ivtFormClient = new IVT_FormClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}
}
}
The error occur is this line of code:
ivtFormClient.TxtFirstName = UserClient.FirstName;
Do not create an instance of a UserControl via constructor but with LoadControl as you have already done in Page_Load. However, you are doing that only if(!IsPostBack). Hence the control is instantiated the next postback via constructor.
Also, you have to recreate dynamic controls on every postback. I would suggest to add the UserControl delaratively to the page. You can hide/show it accordingly. Otherwise you need to create/add it always, best in Page_Init instead of Page_Load.
So this is not best-practise(just add it to the page) but should work as desired:
IVT_FormClient ivtFormClient = null;
protected void Page_Init(object sender, EventArgs e)
{
ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}

Sending data from usercontrol to main page on postback

I want to create a usercontrol for retrieving and filtering a dataset. The problem I'm having is that the controls to be populated are not in the usercontrol, but on the main page on which the usercontrol exists. The reason for this is that the controls that are to be populated are different on each page.
If I could get some help solving the following simplified problem, I will probably be on my way to solve the bigger problem:
<body>
<form id="form1" runat="server">
<div>
<uc1:uc1 ID="uc1" runat="server" />
<asp:Label ID="lbl" runat="server"></asp:Label>
</div>
</form>
</body>
What I want to do is set the label on the main page by clicking a button on the usercontrol. Problem I'm having is that the usercontrol postback happens after the main page.
Thanks!
I managed to solve it by calling Parent.Page. I also implemented an interface so that I can call different pages' methods from the user control. Not sure if it's a good solution, but it will do:
interface IFilter
{
void SetLabel(string text);
}
public partial class uc : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
((IFilter)Parent.Page).SetLabel("changed");
}
}
public partial class _Default : System.Web.UI.Page , IFilter
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
public void SetLabel(string text)
{
lbl.Text = text;
}
}
create a custom event in user control
create a property in usercontrol
fire the event when the button is clicked & set the property value
access the property in the main page in user control's eventhandler

how to access master page control from content page

I have a master page which contains a label for status messages. I need to set the status text from different .aspx pages. How can this be done from the content page?
public partial class Site : System.Web.UI.MasterPage
{
public string StatusNachricht
{
get
{
return lblStatus.Text;
}
set
{
lblStatus.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have tried this, but was unsuccessful in making it work:
public partial class DatenAendern : System.Web.UI.Page
{
var master = Master as Site;
protected void Page_Load(object sender, EventArgs e)
{
if (master != null)
{
master.setStatusLabel("");
}
}
protected void grdBenutzer_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//some code
if (master != null)
{
master.setStatusLabel("Passwort erfolgreich geändert.");
}
}
catch (Exception ex)
{
if (master != null)
{
master.setStatusLabel("Passwort konnte nicht geändert werden!");
}
}
}
}
}
In the MasterPage.cs file add the property of Label like this:
public string ErrorMessage
{
get
{
return lblMessage.Text;
}
set
{
lblMessage.Text = value;
}
}
On your aspx page, just below the Page Directive add this:
<%# Page Title="" Language="C#" MasterPageFile="Master Path Name"..... %>
<%# MasterType VirtualPath="Master Path Name" %> // Add this
And in your codebehind(aspx.cs) page you can then easily access the Label Property and set its text as required. Like this:
this.Master.ErrorMessage = "Your Error Message here";
In Content page you can access the label and set the text such as
Here 'lblStatus' is the your master page label ID
Label lblMasterStatus = (Label)Master.FindControl("lblStatus");
lblMasterStatus.Text = "Meaasage from content page";
It Works
To find master page controls on Child page
Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;
lbl_UserName.Text = txtUsr.Text;
I have a helper method for this in my System.Web.UI.Page class
protected T FindControlFromMaster<T>(string name) where T : Control
{
MasterPage master = this.Master;
while (master != null)
{
T control = master.FindControl(name) as T;
if (control != null)
return control;
master = master.Master;
}
return null;
}
then you can access using below code.
Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null)
lblStatus.Text = "something";
You cannot use var in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.
Crucial bit: Master.Master.
See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl
Example:
'Find the content control
Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")
'now find controls inside that content
Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")
If you are trying to access an html element: this is an HTML Anchor...
My nav bar has items that are not list items (<li>) but rather html anchors (<a>)
See below: (This is the site master)
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
<a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>
Now in your code behind for another page, for mine, it's the login page...
On PageLoad() define this:
HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;
HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;
Now we have accessed the site masters controls, and have made them invisible on the login page.

Resources