Search code examples
asp.netdrop-down-menuselectedvalue

Dropdownlist Reset SelectedValue


I have a DropDownList connected to an ObjectDataSource. In my page load i set the selectedvalue to a specific value depending on the case. How can I in my method selectedindexchanged "reset" the selectedvalue so you still can choose from the other options? Or should I not use selectedvalue to set the defaultvalue of the dropdownlist?

 <asp:DropDownList ID="DropDownList" runat="server" DataSourceID="ObjectDataSource" DataTextField="Type" DataValueField="TypeId" 
    AutoPostBack="true" onselectedindexchanged="DropDownList_SelectedIndexChanged" >
            </asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
        int default = category.TypeId;
        DropDownList.SelectedIndex = default;

}

protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{

    int id = int.Parse(DropDownList.SelectedValue);
    Session["id"] = id;
}

Solution

  • You should only DataBind your DropDownList and set its default value if(!IsPostBack):

    protected void Page_Load(Object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            int default = category.TypeId;
            DropDownList.SelectedValue = default.ToString();
        }
    }
    

    Page.IsPostBack Property