How are DropDown lists retained on postback?

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

Guest

I have an ASP.NET example which programmatically builds a drop down list.

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList ddlCategories;

public class WebForm1 : System.Web.UI.Page
{
if (!IsPostBack)
{
// If page is requested for the first time
ddlCategories.Items.Add("Web development");
ddlCategories.Items.Add("Programming Languages");
ddlCategories.Items.Add("Certifications");
}

aString = ddlCategories.SelectedItem.ToString();
}

When it IS a postback, how is the Drop Down list populated?

I have confirmed that the drop down list is not populated in the .aspx file

I have disabled viewstate for the application, the list is still populated,
however the "SelectedItem" property is lost.

TIA
 
Error in the top of the code. It should be...

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList ddlCategories;

// --- error was here. fixed now. ---
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
.... etc...
 
The values for the dropdown are already rendered and thus will be part of
the page - take a look at the source in the browser. Therefore, it doesn't
depend on viewstate. However, as you see, the selected item does depend on
viewstate since its a server control. That's why you still have the values
in the dropdown, but none of the control property information (which uses
viewstate). Its really not different than building a static web page (html)
and posting back - the values will still be there because they have already
been rendered.
 
Thanks Karch. That answers it for me.

Karch said:
The values for the dropdown are already rendered and thus will be part of
the page - take a look at the source in the browser. Therefore, it doesn't
depend on viewstate. However, as you see, the selected item does depend on
viewstate since its a server control. That's why you still have the values
in the dropdown, but none of the control property information (which uses
viewstate). Its really not different than building a static web page (html)
and posting back - the values will still be there because they have already
been rendered.
 
Back
Top