Du kan binde DropDownList til en datakilde (Datatable, List, DataSet, SqlDataSource osv.).
For eksempel, hvis du vil bruge en DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - Mere komplet eksempel
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
For at indstille en begyndelsesværdi via opmærkningen i stedet for kode bagved, skal du angive valgmulighederne og indstille attributten AppendDataBoundItems til sand:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
Du kan derefter binde DropDownList til en datakilde i koden bag (husk blot at fjerne:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
fra koden bagved, ellers har du to "" elementer.