Accessing controls created dynamically (c#)

后端 未结 3 1559
刺人心
刺人心 2020-12-01 20:10

In my code behind (c#) I dynamically created some RadioButtonLists with more RadioButtons in each of them. I put all controls to a specific Panel. What I need to know is how

3条回答
  •  甜味超标
    2020-12-01 20:55

    You must recreate your controls after each postback.

    ASP.NET is stateless, that is, when you postback a page to the server, your dynamically created controls won't be part of the page anymore.

    Last week I had to overcome this situation once more.

    What did I do? I saved the data that I used to create the controls inside Session object. On PageLoad method I passed that same data to recreate the dynamic controls.

    What I suggest is: Write a method to create the dynamic controls.

    On PageLoad method check to see if it's a postback...

    if(Page.IsPostBack)
    {
       // Recreate your controls here.
    }
    

    A really important thing: assign unique IDs to your dynamically created controls so that ASP.NET can recreate the controls binding their existing event handlers, restoring their ViewState, etc.

    myControl.ID = "myId";
    

    I had a hard time to learn how this thing works. Once you learn you have power in your hands. Dynamically created controls open up a new world of possibilities.

    As Frank mentioned: you can use the "is" keyword this way to facilitate your life...

    if(child is RadioButtonList)
    


    Note: it's worth to mention the ASP.NET Page Life Cycle Overview page on MSDN for further reference.

提交回复
热议问题