Reputation:
How do I load a dropdown list in asp.net and c#?
Upvotes: 8
Views: 27466
Reputation: 14280
wow...rather quick to the point there...
DropDownLists
have an items collection, you call the Add method of that collection.
DropDownList1.Items.Add( "what you are adding" );
Upvotes: 1
Reputation: 7693
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);
Upvotes: 9
Reputation: 344
using Gortok's example, you can databind the list to the dropdownlist also
List<Employee> ListOfEmployees = New List<Employees>();
DropDownList DropDownList1 = new DropDownList();
DropDownList1.DataSource = ListOfEmployees ;
DropDownList1.DataTextField = "TextFieldToBeDisplayed";
DropDownList1.DataValueField = "ValueFieldForLookup";
DropDownList1.DataBind();
Upvotes: 6
Reputation: 57872
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);
}
Upvotes: -2