我正在从 SQL Server 数据库中填充一个下拉列表 DropDownList,如下所示。它可以正常工作,但我不确定它是否是一个好的方法。能否有人解释一下这种方法,并提供一些改进建议?
private void LoadSubjects()
{
ddlSubjects.Items.Clear();
string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "<Select Subject>";
newItem.Value = "0";
ddlSubjects.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
newItem = new ListItem();
newItem.Text = reader["SubjectName"].ToString();
newItem.Value = reader["SubjectID"].ToString();
ddlSubjects.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
//TODO
}
finally
{
con.Close();
}
}
ORDER BY
子句。例如:SELECT SubjectID, SubjectName FROM Students.dbo.Subjects ORDER BY SubjectName ASC
- 这将按照SubjectName升序排列结果。 - Tim