Monday, March 26, 2012

Passing Variable to UserControl From Parent Page

Hi All, I would like to know how to pass a variable to a user control.

An example would be _menu.ascx, which is a user control and is used in every aspx page such as default.aspx. It's properly set using the @dotnet.itags.org.Register tag in the html pages.

CODEBEHIND FOR DEFAULT.ASPX.CS
--------------
public class _default : System.Web.UI.Page
{
````public string strVariable; // want to use this variable in usercontrol

````private void Page_Load(object sender, System.EventArgs e)
````{
````````strVariable = "Hello World";
````}
}

CODEBEHIND FOR _MENU.ASCX.CS
--------------
public abstract class __menu : System.Web.UI.UserControl
{
````protected System.Web.UI.WebControls.Repeater repMenu;

````private void Page_Load(object sender, System.EventArgs e)
````{
````````DataAccess hdlData = new DataAccess();
````````repMenu.DataSource = hdlData.getMenu(??????); // stuck here!!
````````repMenu.DataBind();
````}
}use a Session["name"] object

psi
Is there another way of passing it, instead of using a Session["name"] variable? My variable is actually in the base class (business class), which all the aspx pages inherit from

CODEBEHIND FOR BUSINESS CLASS PAGEHELPER.CS
--------------------
public class PageHelper : System.Web.UI.Page
{
````public string strVariable; // want to use this variable in usercontrol

````public PageHelper()
````{
````````strVariable = "Hello World";
````}
}

CODEBEHIND FOR DEFAULT.ASPX.CS
--------------
public class _default : PageHelper
{
````private void Page_Load(object sender, System.EventArgs e)
````{
````````// this page inherits the PageHelper.cs class, which
````````// sets all the necessary variables.
````}
}

CODEBEHIND FOR _MENU.ASCX.CS
--------------
public abstract class __menu : System.Web.UI.UserControl
{
````protected System.Web.UI.WebControls.Repeater repMenu;

````private void Page_Load(object sender, System.EventArgs e)
````{
````````DataAccess hdlData = new DataAccess();
````````// this needs to get variable in PageHelper.cs class
````````repMenu.DataSource = hdlData.getMenu(??????); // stuck here!!
````````repMenu.DataBind();
````}
}
yes, you should be able to do this, and assess it from the user control:

PageHelper class is public
public string strVariable;

add this property ...
public string StrVariable
{
get{return var;}
set{var = value;}
}

you would then have to instatiate an instance of PageHelper and call the Property:
PageHelper ph = new PageHelper();

//get variable ...
ph.StrVariable

hope that helped
psi
Thank you for all the help psinyc!!!

It works now =)
good

0 comments:

Post a Comment