简体   繁体   中英

Creating Dynamic Controls in Asp.net C#, and caching the controls and binding the Data

I am creating dynamic controls like textbox, dropdowns in Page_Init . After creating control I am binding data to the controls. When page postback happens I have to recreate the controls and rebind the data.

Is there any way I can cache the dynamically created control and just update the newest data to that control. For eg I Create the Textbox then set the value as "abc", when there is postback, i do not want to recreate the Textbox again, or just want to take the control from cache and want to update the latest value say "xyz" to that textbox.

Basically creating the controls first time, cache the control and bind latest data to control on postback.

Thanks Yogesh

Add the code below in your init method

if(!IsPostBack)
{
    //Put your control initzilation here and it will not be triggered on a PostBack
}

You will need to have other logic thow that changes the txt value of the controls that need to be changed.

Creating controls in the Page_OnInit method should take care of the controls retaining their data.

If you're setting data in the code as well, make sure you encapsulate them in

if (!Page.IsPostBack)
{
    //set data here
}

this assures that only the first time the data will be set, instead of overriding every time.


Edit:

As a more complete example:

protected void Page_OnInit(object sender, EventArgs e)
{
    TextBox txt = new TextBox();
    //create more controls
    if (!Page.IsPostBack)
    {
        txt.Text = "initial value";
    }
    Page.Controls.Add(txt);
    //add other controls
}

No EveryTime you have to create it

I do not know but i think that is bug of microsoft or something else but you have to create it everytime

some developers are suggesting that you have to create it in page_Preinit but you will not get any static table or panel control so where did you add control ?

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