Dynamically Populating Dropdownlists

Had to do this today, took a few minutes of google searching

In order to dynamically populate a drop down list use the following logic:

SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = “SELECT STUFF1, [STUFF2] FROM STUFFTABLE”;
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
lstAppointmentType.DataSource = reader;
lstAppointmentType.DataTextField = “STUFF1”;
lstAppointmentType.DataValueField = “STUFF2”;
lstAppointmentType.DataBind();
reader.Close();

Easy stuff once you see it done. Note the column with [] around it is shown so you know to not include the []s when you add to the list.

Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *