简体   繁体   中英

Saving dropdownlist selected value to ViewState

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();

    }       

}
}

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";
        }
    }
}

The Page_Load event fires before the SelectedIndexChanged event. When you change the value in the dropdown list, the vale of the ViewState is still null so the dropdown list is set to "R"?

Tale a look at the following MSDN article discussing page life cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM