Dynamically Change User Control in ASP.Net

后端 未结 4 1376
Happy的楠姐
Happy的楠姐 2020-11-30 05:55

I\'m trying to create a web page that will display an appropriate user control based on the selected value of a drop down list.

Basically the page layout is this:

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 06:41

    What you need to do is keep the last known value of the DropDownList in the Session. Then:

    OnInit:

    • Create whatever control is indicated by the saved value in the session

    SelectionChanged Event

    • Remove whatever you created during OnInit
    • Create and add new control based on new DropDownList selection
    • Save new DropDownList selection in session

    This way, on the next postback after a change you are re-creating the control that ViewState expected to find, and so it's state will be restored.

    Dynamic controls can be very finicky. Often it is easier to create all of the controls you might possible need and set their Visible properties to false. This way they don't render to the browser at all. Then set Visible to true for just the controls you need when you need them.

提交回复
热议问题