Anda dapat mengikat DropDownList ke sumber data (DataTable, List, DataSet, SqlDataSource, dll).
Misalnya, jika Anda ingin menggunakan DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - Contoh lebih lengkap
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"));
}
Untuk menyetel nilai awal melalui markup, alih-alih kode di belakang, tentukan opsi dan setel atribut AppendDataBoundItems ke true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
Anda kemudian dapat mengikat DropDownList ke DataSource di belakang kode (ingat untuk menghapus:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
dari kode di belakang, atau Anda akan memiliki dua item "".