Reputation: 25141
Is it possible to perform a postback and have the viewstate remember the selected value on the following code?
It seems placeholder1.controls.clear() is deleting it.
protected void Page_Load(object sender, EventArgs e)
{
bind();
}
protected void bind()
{
PlaceHolder1.Controls.Clear();
DropDownList ddl = new DropDownList() { AutoPostBack = true, ID="ddl" };
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Items.Add("hi");
ddl.Items.Add("bye");
PlaceHolder1.Controls.Add(ddl);
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
bind();
}
Upvotes: 0
Views: 1180
Reputation: 415600
Is it possible to ... have the viewstate remember the selected value ... ?
ViewState data is restored on postbacks before the load event. If you want ViewState to remember anything for a control, that control must also exist on the page before the load event.
I suspect part of your problem is that you re-create your dropdownlist control when it's selectedindex changes, but nowhere in that code do you set the selectedindex and you therefore destroy the selection every time you set it.
Upvotes: 1
Reputation: 3936
Try calling bind() from Page_Init().
ViewState is loaded after Page_Init() but before Page_Load(), so when you call bind() from Page_Load(), you're calling it after .NET has tried and failed to set the selected value of your DropDownList.
Upvotes: 1
Reputation: 44268
Try removing the PlaceHolder1.Controls.Clear();
method,
and move your Bind()
call out of Page_Load
and into OnInit
You're going to run into Life Cycle Problems the way you're doing things there as the load viewstate & event firing code will have already occured before you recreate you're controls
Upvotes: 1
Reputation: 15673
Why not just hide the PlaceHolder by setting Visible to false? Also, see Truly Understanding Dynamic Controls to get your head around when you need to dynamically inject stuff as dynamic controls are far from straightforward.
Upvotes: 0