I am populating a DropDownList from a SQL Server database as shown below. It works fine, but I’m not sure it’s a good way. Can someone shed some light on this method, and give some improvements?
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();
}
}
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
EDIT – More complete example
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
from the code-behind, or you’ll have two “” items.