如何在 ASP.NET 和 C# 中加载下拉列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/373605/
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 load a dropdown list in ASP.NET and C#?
提问by
How do I load a dropdown list in asp.net and c#?
如何在 asp.net 和 c# 中加载下拉列表?
回答by keithwarren7
wow...rather quick to the point there...
哇...很快就到了那里...
DropDownListshave an items collection, you call the Add method of that collection.
DropDownLists有一个项目集合,您调用该集合的 Add 方法。
DropDownList1.Items.Add( "what you are adding" );
回答by ChadT
You can also do it declaratively:
您也可以声明性地执行此操作:
<asp:DropDownList runat="server" ID="yourDDL">
<asp:ListItem Text="Add something" Value="theValue" />
</asp:DropDownList>
You can also data bind them:
您还可以数据绑定它们:
yourDDL.DataSource = YourIEnumberableObject;
yourDDL.DataBind();
Edit: As mentioned in the comments, you can also add items programatically:
编辑:如评论中所述,您还可以以编程方式添加项目:
yourDDL.Items.Add(YourSelectListItem);
回答by George Stocker
If you have a collection of employee objects, you could add them like so:
如果您有一组员工对象,您可以像这样添加它们:
List<Employee> ListOfEmployees = New List<Employees>();
DropDownList DropDownList1 = new DropDownList();
foreach (Employee employee in ListOfEmployees) {
DropDownList1.Items.Add(employee.Name);
}
回答by awaisj
using Gortok's example, you can databind the list to the dropdownlist also
使用 Gortok 的示例,您也可以将列表数据绑定到下拉列表
List<Employee> ListOfEmployees = New List<Employees>();
DropDownList DropDownList1 = new DropDownList();
DropDownList1.DataSource = ListOfEmployees ;
DropDownList1.DataTextField = "TextFieldToBeDisplayed";
DropDownList1.DataValueField = "ValueFieldForLookup";
DropDownList1.DataBind();

