简体   繁体   中英

Read custom user control state

I add a custom user control to my page, with textboxes and radioboxes, but after each postback, the contents are removed and I don't know how to read the values that were entered in it.

From what I've learned you have to add the user controls on each refresh, but that does not restore their state. I want the values to be stored in the ViewState but that does not happen for some reason.

Note: I need to add multiple user controls on one page, so I need to identify each user control, either trough an ID or a linq expression that selects that user control from my page.

Im programming with C# 4.0

How I add my user control:

    private void AddInstrumentDetailToPage()
    {
        RMAItem lItem = (RMAItem)Page.LoadControl("/Controls/RMAItem.ascx");
        InstrumentDetail.Controls.Add(lItem);
    }

I save the amount of controls I have in the ViewState, and call AddInstrumentDetail() that amount of times, but they appear to be empty. I've read somewhere that I have to add it in Page_Init because view state is not initialised yet, but that doesn't help either.

You need to recreate dynamically added (User-)Controls at latest in Page_Load to maintain ViewState. So you should store the number of already added controls in a ViewState-Property and according to that reload them in Page_Load . You have to sum up this variable with 1 in AddInstrumentDetailToPage .

MSDN: Dynamically Adding User Controls

If you store the number of added controls in a Viewstate variable, you cannot recreate controls in Page's Init-Event because the ViewState-Variable would yet not been reloaded there.

You won't have any ControlState unless you make a PostBack . Refreshing your browser/requesting the same link will just be a fresh start.

By default, any control added to your page are data stored in ViewState and ControlState for your UserControl .

If you are willing to save your contents, I would suggest you save it on Request.Session.Add("yourKey", "yourValue") .

You can access your session with var yourValue = Request.Session["yourKey"]; on your protected void Page_Load(object sender, EventArgs e) method.

Specify an ID for your RMAItem instance, otherwise storing data on ControlState might not work!

private void AddInstrumentDetailToPage()
{
    RMAItem lItem = (RMAItem)Page.LoadControl("/Controls/RMAItem.ascx");
    lItem.ID = "rmaItem1"; //<-- This is important
    InstrumentDetail.Controls.Add(lItem);
}

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM