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

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

4个回答

9
你也可以采用声明式的方式实现它:
<asp:DropDownList runat="server" ID="yourDDL">
    <asp:ListItem Text="Add something" Value="theValue" />
</asp:DropDownList>

您可以使用数据绑定来处理它们:
yourDDL.DataSource = YourIEnumberableObject;
yourDDL.DataBind();

编辑:如评论中所述,您也可以通过编程方式添加项目:

yourDDL.Items.Add(YourSelectListItem);

你也可以通过编程的方式添加下拉列表项:myDropDownList.Items.Add("stuff"); - JohnIdol

6
使用Gortok的示例,您也可以将列表数据绑定到下拉列表中。
List<Employee> ListOfEmployees = New List<Employees>();

DropDownList DropDownList1 = new DropDownList();

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

DropDownList1.DataBind();

1

哇...直截了当地讲解了...

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

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

-2
如果您有一组员工对象,可以像这样添加它们:
List<Employee> ListOfEmployees = New List<Employees>();

DropDownList DropDownList1 = new DropDownList();

foreach (Employee employee in ListOfEmployees) {
DropDownList1.Items.Add(employee.Name);
}

多年以后... 但为什么不直接将List<Employee>绑定到列表上?无需对它们进行迭代。 List<>已经实现了IEnumerable。 - user3308043
6年前,我使用Webforms仅有4个月的经验。现在我会有很多不同的做法。 - George Stocker
我猜这意味着MVC? - user3308043

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接