Updated on Kisan Patel
This tutorial will explain you how to populate or bind DropDownList from database in ASP.NET C#?
Here, we have used below “Countries” table to populate DropDownList with data.
Next, we have added DropDownList
control inside Default.aspx
page as shown in below code.
<form id="form1" runat="server"> <div> <label for="dropdown_country">Select Country</label> <asp:DropDownList ID="dropdown_country" runat="server"></asp:DropDownList> </div> </form>
Next, we have added below C# code inside Default.aspx.cs
Page_Load event.
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Web.UI.WebControls; namespace DropDownDemo { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("Select * from Countries", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); con.Close(); //Set the DataSource for DropDown dropdown_country.DataSource = dt; dropdown_country.DataValueField = "Id"; dropdown_country.DataTextField = "CountryName"; dropdown_country.DataBind(); dropdown_country.Items.Insert(0, new ListItem("Select Country", "")); } } } }
Demo