Asp.NET DropDownList SelectedItem.Value not changing

Bahamut picture Bahamut · Apr 27, 2012 · Viewed 43.5k times · Source

markup:

            <div style="float:left;margin-top:15px;width:80px">
                <asp:DropDownList ID="MyList" runat="server" Width="100px"></asp:DropDownList>
            </div>

code:

        // clear vehicles list
        MyList.Items.Clear();

        // add 'all' option
        MyList.Items.Add(new ListItem("ALL", "0"));

        // add assets
        foreach (CustomClass item in items)
            MyList.Items.Add(new ListItem(item.Name, item.ID.ToString()));

No event triggering for SelectedIndexChanged since it's not necessary.

When I click the button for postback, the value of the selecteditem remains the value of the first item in the DropDownList. What am I missing?

NOTE Please stop replying and editing posts. We may leave it as it is since it has been answered already.

Answer

Leniel Maccaferri picture Leniel Maccaferri · Apr 27, 2012

If you're databinding in Page_Load, you're essentially also resetting the SelectedItem.

You should wrap whatever binding code that exists in Page_Load inside an if(!IsPostBack) block.

if(!Page.IsPostBack)
{

    // Your binding code here ...

}