<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

Passing Data Between User Controls

by Tim 15. February 2011 16:31

The key to understanding how to pass data between User Controls lies in the Page Life cycle. Here is a snippet of the Page Life Cycle that we can reference for the following task:

Page: Load
Control: DataBind
Control: Load
Page: EnsureChildControls
Page: LoadComplete
Page: EnsureChildControls
Page: PreRender
Control: EnsureChildControls
Control: PreRender

We have an ASPX page with two User Controls (uc1 and uc2) and we want to set a value in uc1 and pass that value to uc2.

The ASPX page will act as the dealer of the variables. First we must setup public properties in uc1 and uc2 in order for the ASPX page to reference them:

string _Name;

    public string Name
    {
        get {
            return _Name;
        }
        set {
            _Name = value;
        }
    }

We can then set an arbitrary name in the Page_Load event of uc1, we will display it in a label so that we can see the order of life cycle events.

Name = "Isambard Kingdom Brunel";
Label1.Text = "uc1 = " + Name;

Because the variable has been set in the Page_Load event of uc1, we can't reference the variable in the Page_Load event of the ASPX page (see the life cycle above) so we have to reference it in the Page_PreRender event. We then want to pass the variable to uc2:

Label1.Text = "Get from uc1 = " + uc1.Name;
uc2.Name = uc1.Name;

In uc2 we can see that the variable will be an empty string in the Page_Load event (having been sent from the ASPX Page_PreRender event) but we can get the passed value in the Control's Page_PreRender event:

Label1.Text = "uc2 = " + Name;

When we run the program we get the following results:

uc1 = Isambard Kingdom Brunel
uc2 = Isambard Kingdom Brunel
Get from uc1 in ASPX page = Isambard Kingdom Brunel

The variable set in uc1 has successfully been referenced by the ASPX page and passed to uc2.

Tags: ,

ASP.NET | C#

Comments are closed