Zed_Blade
Zed_Blade

Reputation: 1081

Cross UserControl property setting and persisting values

I'm using a set of UserControls on a ASP.NET application which I'm maintaining.

I have a page which renders a set of custom UserControls. On one of these controls, lets say ucA, I may have a little Javascript Popup which render another UserControl and let's call this one ucB. On ucA I've defined a public property which sets or gets values from a hiddenField defined in ucA:

<asp:HiddenField ID="hidWorkDirName" runat="server" />

and the property definition:

public string _hidWorkDirName
{
    get { return hidWorkDirName.Value; }
    set { hidWorkDirName.Value = value; }
}

My ucB only shows a Textbox which, upon submit, should set the value of the hidWorkDirName:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    ucA parent = (ucA)this.Parent; //this, being ucB
    parent._hidWorkDirName = txtName.Text; //the TextBox value being set on ucA
}

While debugging I can see that the value is set correctly.

Now, ucA also has a Submit button (both submits are for different things) on which I want to read the value of the hidWorkDirName. But no matter what I try the value I get is always an empty string as if nothing had been set.

I've tried reading the value directly from the hiddenField and from the property itself (_hidWorkDirName) but I never get the value I've set previsouly.

Why is this happening?

Upvotes: 1

Views: 69

Answers (1)

Sam
Sam

Reputation: 2917

This is because the Hiddenfield hidWorkDirName could get reset during the Page_Load. Try a different approach using ViewState.

Here's your property with ViewState

public string _hidWorkDirName
{
    get
    {
        if (ViewState["WorkDirName"] != null)
        {
            return (string)ViewState["WorkDirName"];
        }
        return string.Empty;
    }
    set
    {
        ViewState["WorkDirName"] = value;
    }
}

Upvotes: 1

Related Questions