Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET DropDownList SelectedItem.Value not changing

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.

like image 655
Bahamut Avatar asked Apr 27 '12 03:04

Bahamut


2 Answers

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 ...

}
like image 133
Leniel Maccaferri Avatar answered Nov 12 '22 08:11

Leniel Maccaferri


Your code is probably executing after postback too, clearing the box, hence losing selection and all.

If so, try wrapping the code in something like if( !Page.IsPostBack ) { ... }.

like image 5
Meligy Avatar answered Nov 12 '22 10:11

Meligy