ElectiveRob
ElectiveRob

Reputation: 13

Asp.net dynamic dropdownlist

I want to create a dynamic DropDownList in ASP.NET, but after postback the DropDownList loses the selected value. Recreating the control on postback has no effect (ViewState, same ID).

Im wondering if the ViewState of the DropDownList is not working. I've created dynamic TextBoxes before, and they retain the value after postback.

I'm thinking to get the value from the form post like in this article:

http://www.aspsnippets.com/Articles/Creating-Dynamic-DropDownList-Controls-in-ASP.Net.aspx

Is this a common solution to this problem?

Upvotes: 1

Views: 7058

Answers (2)

James Johnson
James Johnson

Reputation: 46047

You have to recreate the control before ViewState is loaded, like during OnInit or OnPreInit for example. You also need to assign the same ID to the control every time the page is posted back, because ViewState uses the control ID to reload the values.

Upvotes: 0

Paul
Paul

Reputation: 36319

If you're not, you should be dynamically creating the drop-down on Init, and then you can read/write their properties on or after Load. Have a look at this article: https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx which describes it in more detail.

Upvotes: 4

Related Questions