15

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.

Bahamut
  • 1,821
  • 8
  • 28
  • 49

5 Answers5

45

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

}
Leniel Maccaferri
  • 94,281
  • 40
  • 348
  • 451
4

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 ) { ... }.

Meligy
  • 32,897
  • 11
  • 79
  • 103
0

So this answer is the "obvious" solution to the most common cause. However, there is one more surprising issue that can cause this! My list values came from a database and the values had linefeed and carriage return: "\r\n". These values look like an innocent space, but actually they are not! My solution was to remove these hidden Char values. Hope it helps.

-1

Yes you are missing to add drop down list Autopostback=true..

Please try with following in your .aspx page

Vimal bhatt
  • 285
  • 1
  • 2
  • 7
-1

hey for first index to add all not required to add. you need to insert on particular index number

MyList.Items.Insert(0, "ALL");
Saroop Trivedi
  • 2,196
  • 6
  • 28
  • 46
  • 1
    This answer would not make any difference since it just adds an item. Question has been answered already, thank you. – Bahamut Apr 27 '12 at 13:01