C# 如何将 DropDownList 中的项目设置为默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1983713/
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
How do I set an item in a DropDownList as the default value?
提问by Nevin Mathai
How do I set an item in a DropDownList as the default value in ASP.NET?
如何将 DropDownList 中的项目设置为 ASP.NET 中的默认值?
SomeDropDownList.DataSource =GetSomeStrings();
采纳答案by Ariel
There are two ways to do it:
有两种方法可以做到:
Set the
SelectedValue
to the value you want as the defaultDropDownList.SelectedValue = "value"
. This is very simple but will result in an error if the dropdown already has aSelectedValue
Set the actual item
DropDOwnList.Items.FindByValue("value").Selected = true;
which should not result in an error in case there already is a selected item.
将 设置为
SelectedValue
您想要的值作为默认值DropDownList.SelectedValue = "value"
。这很简单,但如果下拉菜单已经有一个SelectedValue
设置实际项目
DropDOwnList.Items.FindByValue("value").Selected = true;
,如果已经存在选定项目,则不应导致错误。
回答by SLaks
Set the SelectedValue
property
设置SelectedValue
属性
回答by alexphi
You can bind the DropDownList to the data source, and then set the SelectedValue:
您可以将 DropDownList 绑定到数据源,然后设置 SelectedValue:
someDropDownList.DataSource = GetSomeStrings();
someDropDownList.DataBind();
someDropDownList.SelectedValue = "default value";
You could also select the default item by index, using the SelectedIndex property:
您还可以使用 SelectedIndex 属性按索引选择默认项:
someDropDownList.SelectedIndex = 0;