Search code examples
asp.netautopostback

Why ispostback not working with dropdown box


I want to keep selected item after page reload:

Excerpt from .aspx:

    <asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="true" 
        onselectedindexchanged="MyDropDown_SelectedIndexChanged">

    </asp:DropDownList>

Exerpt from .cs in page_load

        if (!IsPostBack)
        {
            PopulateDropDownList();
        }

with

    private void PopulateDropDownList()
    {
        MyDropDown.Items.Add("1");
        MyDropDown.Items.Add("2");
    }

    protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect(Request.RawUrl);
    }

Solution

  • Response.Redirect refresh the page and you will loose view state that will have selected index. You can put the selected index in session before redirecting.

    protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["MyDropDownSelectedIndex"] = MyDropDown.SelectedIndex.ToString();
        Response.Redirect(Request.RawUrl);
    }