User Control; read value from hosting aspx code-behind

G

Gene

I have a number of aspx pages on which a single user control appears. All of
the aspx pages and the user control make user of code-behind modules. I need
for logic in the user control's code-behind to read the current value of a
variable in the hosting aspx page's code-behind. How is this accomplished?

Thanks.
 
S

Steve C. Orr [MVP, MCSD]

From your user control code-behind you can use code similar to this:

If Page.SomePublicProperty = "Whatever" Then ...
 
C

Curt_C [MVP]

On the page make sure it's public

From the control, something like
string myVar = this.ParentPage.variableName.ToString();
 
G

Gene

Thanks Curt and Steve: Now a related question: I set the public variable
from the aspx page_load event procedure, and want to I read that public
variable from the page_load event procedure of the user control. In order
for this to work as expected, I need for the page_load event of the aspx to
fire *before* the page_load of the user control. Is that a safe assumption?

Thanks again.
 
C

Curt_C [MVP]

put in a break point and test it to see.
You may need to move it up to the intialize event though

--
Curt Christianson
Owner/Lead Developer, DF-Software
www.Darkfalz.com
 
G

Gene

I've tried the initial task using the syntax both you and Steve recommended,
however, either way I get compile-time errors, the message of which is
something like:
'System.Web.UI.Page' does not contain a definition for 'myPublicVariable'

It makes sense that such compile-time errors would occur, as the user
control - at compile time - does not know which aspx page will be hosting
it, and the compiler therefore cannot know where to look to see if the
public property exists. Am I confused? Is it possible to do this without
getting the compile-time error and I'm just missing something.

Thanks.
 
M

Matt Berther

Hello Gene,
see if the public property exists. Am I confused? Is it possible to do
this without getting the compile-time error and I'm just missing
something.

Derive your own page class.

Ex:

public class MyPage : System.Web.UI.Page
{
public string myPublicVariable; // Note: I would never make this as a field in production code. This is just to illustrate.
}

From your user control:

MyPage myPage = (MyPage)this.Page;
string s = myPage.myPublicVariable;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top