質問

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);
    }
役に立ちましたか?

解決

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

他のヒント

You need to populate the drop down list in the Page init event. If you do that during Page load event the view state cannot be restored correctly (because the drop down list is not populated before Page load event) so the on selected index changed event cannot be fired.

EDIT: you may want to cache the data which populate the drop down list to save some around trip to the database. I think you do not need to redirect in the on selected index changed event too.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top