Using ‘Using’ to Populate a DropDownList

Found a new way to populate a DropDownList using the ‘using’ statement.

DataTable dtTour = new DataTable();
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;

using (SqlConnection con = new SqlConnection(strConnection))
{

try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
adapter.Fill(dtTour);

ddlTour.DataSource = dtTour;
ddlTour.DataValueField = "TourId";
ddlTour.DataTextField = "TName";
ddlTour.DataBind();
}
catch (Exception ex)
{
// Handle the error
}

}

// Add the initial item
ddlTour.Items.Insert(0, new ListItem("", "0"));

You can find out more about ‘Using’ here.

Leave a comment