如何在ASP.NET和C#中加载下拉列表?

如何在ASP.NET和C#中加载下拉列表?,c#,asp.net,C#,Asp.net,如何在asp.net和c#中加载下拉列表?哇…很快就说到点子上了 DropDownLists有一个items集合,您可以调用该集合的Add方法 DropDownList1.Items.Add( "what you are adding" ); 您还可以声明式地执行此操作: <asp:DropDownList runat="server" ID="yourDDL"> <asp:ListItem Text="Add something" Value="theValue"

如何在asp.net和c#中加载下拉列表?

哇…很快就说到点子上了

DropDownLists
有一个items集合,您可以调用该集合的Add方法

DropDownList1.Items.Add( "what you are adding" );

您还可以声明式地执行此操作:

<asp:DropDownList runat="server" ID="yourDDL">
    <asp:ListItem Text="Add something" Value="theValue" />
</asp:DropDownList>
编辑:如评论中所述,您还可以通过编程方式添加项目:

yourDDL.Items.Add(YourSelectListItem);

如果您有一组employee对象,您可以这样添加它们:

List<Employee> ListOfEmployees = New List<Employees>();

DropDownList DropDownList1 = new DropDownList();

foreach (Employee employee in ListOfEmployees) {
DropDownList1.Items.Add(employee.Name);
}
List ListOfEmployees=新列表();
DropDownList DropDownList1=新的DropDownList();
foreach(员工列表中的员工){
DropDownList1.Items.Add(employee.Name);
}

使用Gortok的示例,您还可以将列表数据绑定到dropdownlist

List<Employee> ListOfEmployees = New List<Employees>();

DropDownList DropDownList1 = new DropDownList();

DropDownList1.DataSource = ListOfEmployees ;
DropDownList1.DataTextField = "TextFieldToBeDisplayed";
DropDownList1.DataValueField = "ValueFieldForLookup";

DropDownList1.DataBind();
List ListOfEmployees=新列表();
DropDownList DropDownList1=新的DropDownList();
DropDownList1.DataSource=员工列表;
DropDownList1.DataTextField=“TextFieldToBeDisplayed”;
DropDownList1.DataValueField=“ValueFieldForLookup”;
DropDownList1.DataBind();

您还可以通过编程方式添加myDropDownList.Items.add(“stuff”);[已经在很多方面得到了回答…][1][1]:几年后。。但是为什么不直接将列表绑定到列表呢?不需要重复它们。List已经实现了IEnumerable。@user330843 6年前,我使用Webforms总共4个月了。现在我有很多不同的想法。我猜这意味着MVC?
List<Employee> ListOfEmployees = New List<Employees>();

DropDownList DropDownList1 = new DropDownList();

DropDownList1.DataSource = ListOfEmployees ;
DropDownList1.DataTextField = "TextFieldToBeDisplayed";
DropDownList1.DataValueField = "ValueFieldForLookup";

DropDownList1.DataBind();