Accessing parent properties in UserControls from different aspx page

55 Views Asked by At

There is a aspx page which makes use of UserControl as follows.

Page1.aspx.cs

public class Page1
{
  public string Code {get;set;}
 ....

}

In the Page1.aspx a user control called "UsrControl"

<@Register TagPrefix="Usr" NameSpace="UsrControl">

I have the following code in UsrControl.

 public class UsrControl : Label
    {
      private Page1 _page1;
      
     protected override void OnInit(EventArgs e)
      {
        _page1 = (Page1)Page;
        string test = _page1.Code;
      }
.....
    }

In the usercontrol , the parent page is harcoded and from there the property of parent page (Page1) is being used .

Now the thing is I have one more aspx page Page2 which has same set of properties as Page1(Code) needed to invoke "UsrControl"

How can I refactor "UsrControl" to have the capability of accepting Page1 and Page2 and execute the code ? Should reflection be used?

2

There are 2 best solutions below

0
VDWWD On

It would be easier to turn it around. Set the Code value from the page to the UserControl instead of getting it from the Page.

So in your UserControl add a property Code

public string Code { get; set; }

Then you can set that property from the aspx page of the parent.

<Usr:WebUserControl1 ID="WebUserControl1" runat="server" Code='<%# Code %>' />

And then call DataBind(); in Page_Load of the parent page.

public string Code { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    Code = "This is a test.";

    DataBind();
}

You can also add the UserControl programatically on the parent page and set Code from there.

public WebUserControl1 UsrControl { get; set; }
public string Code { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    Code = "This is a test.";

    UsrControl = (WebUserControl1)LoadControl("~/WebUserControl1.ascx");
    UsrControl.Code = Code;
    PlaceHolder1.Controls.Add(UsrControl);
}
1
Wiktor Zychla On

Just make an interface that shapes your data provider

public class IPageDataProvider
{
  string Code {get;set;}
}

and implement this interface in both your pages

public class Page1 : IPageDataProvider
{
  public string Code {get;set;}
  ....

}

public class Page2 : IPageDataProvider
{
  public string Code {get;set;}
  ....

}

After that, refactor your user control

public class UsrControl : Label
{
  private IPageDataProvider _pageDataProvider;
  
  protected override void OnInit(EventArgs e)
  {
    this._pageDataProvider = this.Page as IPageDataProvider;
    if ( this._pageDataProvider != null )
    {
      string test = this._pageDataProvider.Code;
    }
    else
    {
      // parent page doesn't implement the interface
    }
  }
}