Dynamically Change User Control in ASP.Net

我是研究僧i 提交于 2019-11-27 04:26:33

This is the classic tear-your-hair-out problem with ASP.Net webforms. You have several options:

1) This is a bit of a hack, since it goes outside the intended page lifecycle a bit, but in my experience it's the most direct way of dealing with the problem. When the page posts back from the drop down selection event, simply poll Request["MyDropDownID"] for the selected value of the drop down control during Init() - don't wait for the OnMyDropDownChanged() event to set up your page.

2) Implement your own ViewState handling for your user controls. This requires digging into the ViewState documentation and overriding a number of methods.

3) Joel's solution. He beat me to it but I was trying to get first post :p

Other options involve posting values using javascript and such, but those get really messy.

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.

HectorMac

If the list of options is not too big, you could just render all the user controls statically and use JavaScript/jQuery to show/hide the appropriate controls based on the value of the dropdown (onchange js event). You can use the dropdown value to extract the appropriate values from the user controls when saving.

You avoid the pain of dealing with dynamic controls, provide a more responsive UI when selecting from the dropdown (no postback), etc...

Don't add the control in the SelectedIndexChanged handler, add it during Page_Load. You'll just have to test the value of the dropdown each time the page loads, and load the correct control for that value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!