Binding dropdown is a common need in ASP.Net. The below code snippet is used to bind the datatable values to the dropdown list.
Markup:
Markup:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList runat="server" ID="ddlCity"> </asp:DropDownList> </div> </form> </body> </html>Code behind:
protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { //Substitute your DB and Server name below string conString = @"Data Source=Your_DBServer_Name;Initial Catalog=Your_DB_Name;Integrated Security=True"; DataTable dtCity = new DataTable("City"); // Create Connection and get the DB values using (SqlConnection connection= new SqlConnection(conString)) { SqlCommand command = new SqlCommand(conString,connection); command.CommandText = "Select city_code,city_description from tblCity"; SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(dtCity); } // Set the Datasource ddlCity.DataSource = dtCity; ddlCity.DataValueField = "city_code"; ddlCity.DataTextField = "city_description"; // Finally Bind it ddlCity.DataBind(); } }