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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:24:34  来源:igfitidea点击:

How do I set an item in a DropDownList as the default value?

c#asp.netdrop-down-menu

提问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:

有两种方法可以做到:

  1. Set the SelectedValueto the value you want as the default DropDownList.SelectedValue = "value". This is very simple but will result in an error if the dropdown already has a SelectedValue

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

  1. 将 设置为SelectedValue您想要的值作为默认值DropDownList.SelectedValue = "value"。这很简单,但如果下拉菜单已经有一个SelectedValue

  2. 设置实际项目DropDOwnList.Items.FindByValue("value").Selected = true;,如果已经存在选定项目,则不应导致错误。

回答by SLaks

Set the SelectedValueproperty

设置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;