Asp.NET DropDownList SelectedItem.Value not changing

怎甘沉沦 提交于 2020-07-15 06:39:04

问题


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.


回答1:


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

}



回答2:


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




回答3:


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.




回答4:


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

Please try with following in your .aspx page




回答5:


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

MyList.Items.Insert(0, "ALL");


来源:https://stackoverflow.com/questions/10344469/asp-net-dropdownlist-selecteditem-value-not-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!