1

The scenario is very simple. I have an aspx page with a user control. I want to set a value and get a response from usercontrol on aspx page's pageload. The SET job is done, but can't GET the response. It's always empty. I tried two methods, but none of them worked.

ASPX PAGE

<uc1:ucContent ID="Content1" runat="server" />

CODE BEHIND

protected void Page_Load(object sender, EventArgs e)
{
    // SET job is working without any problem
    Content1.ItemName = "X";

    //METHOD ONE:
    Page.Title = Content1.MetaPageTitle;

    //METHOD TWO:
    HiddenField hdnPageTitle = (HiddenField)Content1.FindControl("hdnMetaPageTitle");
    Page.Title = hdnPageTitle.Value;
}

USER CONTROL

protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(itemName))
    {
         // GET DATA FROM DB

         // METHOD ONE:
         hdnTitle.Value = DB.DATA;

         // METHOD TWO:
         metaPageTitle = DB.DATA;
    }
}

private string metaPageTitle;
public string MetaPageTitle
{
    // METHOD ONE:
    get { return metaPageTitle; }

    // METHOD TWO:
    get { return hdnTitle.value; }
}

EDIT

itemName is a UserControl property to get a value from Parent Page:

private string itemName;
public string ItemName
{
    set { itemName = value; }
}

Thanks for your kind help in advance!

Kardo
  • 1,658
  • 4
  • 32
  • 52

1 Answers1

2

I think that the problem is that the page's Page_Load is triggered before the UserControl(Have a look: asp.net: what's the page life cycle order of a control/page compared to a user contorl inside it?).

So you could set the property in Page_init:

In your UserControl:

protected void Page_Init(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(itemName))
    {
         // GET DATA FROM DB

         hdnTitle.Value = DB.DATA;
    }
}

Now this should work in your page's Page_Load:

Page.Title = Content1.MetaPageTitle;

Normally i would prefer another kind of communication between a Page and a UserControl. It's called event-driven communication and means that you should trigger a custom event in your UC when the MetaPageTitle changed (so in the appopriate event-handler).

Then the page can handle this specific event and react accordingly.

Mastering Page-UserControl Communication - event driven communication

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks for answer! Now the problem is I can't get values in User Control side. I mean "itemName" is always empty. – Kardo Aug 11 '14 at 14:10
  • I have no idea what `itemName` is, you haven't shown it. – Tim Schmelter Aug 11 '14 at 14:16
  • @Kardo: then provide a method `SetItemName` which sets this property and stores it somewhere(f.e. in ViewState,HiddenField,Session). In this method you should call your `// GET DATA FROM DB`-logic. – Tim Schmelter Aug 11 '14 at 14:28