C# – Saving dropdownlist selected value to ViewState

cdrop-down-menunetselectedindexchangedviewstate

I have a dropdownlist that when changed will save the new value into a ViewState variable, so that after a postback, the dropdownlist will retrieve it's selected value from ViewState if previously set.

When it tries to store the selected value in DropDownList1_SelectedIndexChanged to ViewState, it always inserts the original value and not the updated one. In this case, the ViewState is always "R" and never changes according to other selected values.

Any ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication11
{
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (ViewState["List1_Value"] != null)
        {
            DropDownList1.SelectedValue = ViewState["List1_Value"].ToString();

        }
        else
        {
            DropDownList1.SelectedValue = "R";

        }

    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["List1_Value"] = DropDownList1.SelectedValue.ToString();

    }       

}
}

Best Answer

Change the Page_Load method to bypass the dropdown list code when it is not a post back.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (ViewState["List1_Value"] != null)
        {
            DropDownList1.SelectedValue = ViewState["List1_Value"].ToString();
        }
        else
        {
            DropDownList1.SelectedValue = "R";
        }
    }
}
Related Topic