您可以将DropDownList绑定到数据源(DataTable,List,DataSet,SqlDataSource等)。
例如,如果您想使用数据表:
ddlSubject.DataSource = subjectsTable;ddlSubject.DataTextField = "SubjectNamne";ddlSubject.DataValueField = "SubjectID";ddlSubject.DataBind();
编辑-更完整的示例
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"));}要通过标记而不是代码隐藏设置初始值,请指定选项并将AppendDataBoundItems属性设置为true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true"> <asp:ListItem Text="<Select Subject>" Value="0" /></asp:DropDownList>
然后,您可以将DropDownList绑定到背后代码中的数据源(只记得删除:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));从后面的代码中,否则您将有两个“”项。



