get value of dynamic control on postback?

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);
}
 
G

Guest

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
 
E

Eliyahu Goldin

Place the code for control creting in the PreInit event. The reason is
because LoadViewState occurs between Init and Load events.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,815
Latest member
treekmostly22

Latest Threads

Top