C# Asp.NET DropDownList SelectedItem.Value 不变
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10344469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asp.NET DropDownList SelectedItem.Value not changing
提问by Bahamut
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.
SelectedIndexChanged 没有事件触发,因为它不是必需的。
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?
当我单击回发按钮时,所选项目的值仍然是 DropDownList 中第一个项目的值。我错过了什么?
NOTEPlease stop replying and editing posts. We may leave it as it is since it has been answered already.
注意请停止回复和编辑帖子。我们可以保持原样,因为它已经得到了回答。
采纳答案by Leniel Maccaferri
If you're databinding in Page_Load, you're essentially also resetting the SelectedItem.
如果您在 中进行数据绑定Page_Load,那么您实际上也是在重置 SelectedItem。
You should wrap whatever binding code that exists in Page_Loadinside an if(!IsPostBack)block.
你应该换什么约束力存在于代码Page_Load内部if(!IsPostBack)块。
if(!Page.IsPostBack)
{
// Your binding code here ...
}
回答by Meligy
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 ) { ... }.
如果是这样,请尝试将代码包装在类似if( !Page.IsPostBack ) { ... }.
回答by Vimal bhatt
Yes you are missing to add drop down list Autopostback=true..
是的,您缺少添加下拉列表 Autopostback=true..
Please try with following in your .aspx page
请尝试在您的 .aspx 页面中执行以下操作
回答by Saroop Trivedi
hey for first index to add all not required to add. you need to insert on particular index number
嘿第一个索引添加所有不需要添加。您需要插入特定的索引号
MyList.Items.Insert(0, "ALL");
回答by Oliver Lundt
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.
所以这个答案是最常见原因的“明显”解决方案。但是,还有一个更令人惊讶的问题会导致这种情况!我的列表值来自数据库,这些值有换行和回车:“\r\n”。这些值看起来像一个无辜的空间,但实际上它们不是!我的解决方案是删除这些隐藏的 Char 值。希望能帮助到你。

