Friday, 29 January 2016

How to bind DropDownList from DataBase in ASP.NET with C#

In this tutorial, I will explain you how to bind DropDownList control from DataBase in with C#.

Related Articles

Creating SQL Table

First, we need to create table, give name as tblCity. And insert some dummy values into table. Below is the script.

create table tblCity
Id int identity,
City varchar(10)
insert into tblCity values('Mumbai')
insert into tblCity values('Delhi')
insert into tblCity values('Pune')

In Web.config File

Write your database connection string in web.config file within <connectionStrings> tag.

    <add name="MyConnString" connectionString="server=XXXX;database=XXXX;uid=XXXX;password=XXXX;" 

In designer file

In designer file, create a DropDownList control named ddlCity.

<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>

Namespaces Used

Include the below Namespaces.

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

Complete C# Code

Here, on Page_Load event, we are calling BindDropDown() method. We are getting city data from database by using in-line SQL query, after that assigning text and value field of DropDownList control. We are inserting new ListItem as "--select--" at 0th index.

        //retrieving connection string from web.config file
        string MyConnString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
        SqlConnection con=null;
        SqlCommand cmd=null;
        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)

        public void BindDropDown()
            con = new SqlConnection(MyConnString);
            cmd = new SqlCommand("select Id,City from tblCity", con);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            ddlCity.DataSource = ds;
            ddlCity.DataTextField = "City";
            ddlCity.DataValueField = "Id";
            ddlCity.Items.Insert(0, new ListItem("--select--"));


Output will be shown as below.

Bind DropDownList control from DataBase in

1 comment:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive