get value of dynamic control on postback?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

For simplicity sake,

How do you get the value of selected dropdown on a postback? I understand
for a dynamic control, you need to re-create it on each postback, but how do
I modify the code to grab the SelectedValue?

protected void Page_Load(object sender, EventArgs e)
{
DropDownList list = new DropDownList();
list.ID = "DropDownList1";
list.Items.Add(new ListItem("1", "One"));
list.Items.Add(new ListItem("2", "Two"));
list.Items.Add(new ListItem("3", "Three"));
PlaceHolder1.Controls.Add(list);
}
 
Hi,
So, the controls that were dynamically created are no longer there and
consequently the values returned from these controls have no place to go.
They are lost in the viewstate.

In order to catch these values the dynamically generated controls needs to
be re-generated at Page_Load. The important thing is to assign the same ID to
each control. The ViewState uses the ID property of the Control objects to
reinstate the values.

If you create a dynamic dropdownlist, conditionally, say in response to some
other control's click event. Then, on PostBack, you recreate a "new" dropdown
with the same object name, then "magically" that new dropdown becomes the
dynamically-created dropdown. You get all of the user-initiated and
code-generated properties.
ref:http://www.codeproject.com/aspnet/retainingstate.asp?df=100&forumid=14609&exp=0&select=1495875
 
Place the code for control creting in the PreInit event. The reason is
because LoadViewState occurs between Init and Load events.
 
Back
Top