How to bind Dropdownlist with database in - ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

How to bind Dropdownlist with database in

Introduction: In this post I will explain how we can bind the Dropdownlist control with database in
Open the Visual Studio>Go to File>New>Website. Add the Connectionstring in web.config file of website.
    <add name="connection" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
        <compilation debug="true" targetFramework="4.0" />

After that add new web form to website. Take a Dropdownlist from Toolbox>>Standard.
<asp:DropDownList ID="ddlstate" runat="server">

I have created a table name TB_STATE.

Here ID is primary key.
Now go to the aspx.cs page, firstly add namespace and create a function to fill dropdown.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
  private void Filldropdown()
            SqlCommand cmd = new SqlCommand("select * from TB_STATE", con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            ddlstate.DataSource = dt;
            ddlstate.DataValueField = "ID";
            ddlstate.DataTextField = "STATE";
            ddlstate.Items.Insert(0,new ListItem("--Select--","0"));
        catch (Exception ex)
            Response.Write("Error Occured"+ex.Message);

Now debug the application and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.