urz shah
urz shah

Reputation: 481

How can access property of .aspx in the user control?

I have an .aspx page in which I have a property. Now i create a user control and drop it on the page. Now how can i access that property in code behind of usercontrol.

Upvotes: 0

Views: 4889

Answers (2)

Jupaol
Jupaol

Reputation: 21355

The best way is to expose a public property in the UserControl and assign that property from the ASPX page:

By code:

var uc = this.myUserControl as MyCuserControlType;

uc.CustomUserControlProperty = this.MyPageProperty;

Declaratively

<uc:MyUserControlType1 runat="server= ID="myUserControl" CustomUserControlProperty="<%# this.MyPageProperty %>" />

Note: If you want to use declarative markup you would need to call this.DataBind(); in code to force the binding

Edit 1

In case you want to do the opposite (pass a value from the control to the page in response to an event) you could declare your own custom event in the user control and fire it when needed it.

Example:

User control code behind*

public event Action<string> MyCustomEvent = delegate{};

....
// somewhere in your code
this.MyCustomEvent("some vlaue to pass to the page");

Page markup

<uc:MyUserControl1 runat="server" onMyCustomEvent="handleCustomEvent" />

Page code behind

public void handleCustomEvent(string value)
{
    // here on the page handle the value passed from the user control
    this.myLabel.Text = value;
    // which prints: "some vlaue to pass to the page"
}

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If a user control needs to access something on the parent page, then maybe this user control should have included it as its own property which could be set from the parent. Ideally user controls should be independent from any parent context or other user controls on the page, otherwise they really are not something reusable. They need to be self contained and configurable throughout their the properties they are exposing.

Upvotes: 2

Related Questions