Simplest way to populate dropdownlist in asp.net (code behind)?
You can use DataTextField and DataValueField properties.
ListControl.DataTextField Property
DropDownList1.DataSource = drpdt;
DropDownList1.DataTextField="StringValue";
DropDownList1.DataValueField="CurrencyValue";
DropDownList1.DataBind();
Or add ListItem one at a time.
ASP.Net DropDownList DataTextField Multiple Columns
All databound controls can be bound to DataTable and any object that Implements IEnumerable (e.g. Array of String). DropdownList is a databound control, so the answer is Yes.
if (dt.Rows.Count > 0)
{
DropDownList1.DataTextField = "FlightDescription";
DropDownList1.DataValueField = "FlightID";
DropDownList1.DataSource = drpdt;
DropDownList1.DataBind();
}
You can also set the DataXXXField properties from the MarkUp
<asp:DropdownList ID="DropDownList1" runat="server"
DataTextField="FlightDescription" DataValueField="FlightID">
</asp:DropdownList>
The solutions that Win and codingbiz suggested are the easiest, but only for the easiest scenarios. Not every DropDown is required to be bound like that. Sometimes I have instances where I will need to bind two (or more) values to a Listitem, leading me to do something like what your example did by iterating through the DataTable rows, but instead doing...
foreach (DataRow dr in dt.Rows) {
DropDownList1.Items.Add(new ListItem(dr["flightdate"], dr["flightnum"] + ":" + dr["flightcarrier"]));
}
Later I can do a String.Split(":")(0)
or String.Split(":")(1)
to get the first and second ListItem values.
All in all, it really depends on what your needs are.