我正在从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();
}
}