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

 Print 
 Posted By :  ASPArticles
 Posted Date: Jan 29, 2016
 Category :  , ,
 Post Hits : 150

In this tutorial, I will explain you how to bind DropDownList control from DataBase in asp.net 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.

<configuration>
  <connectionStrings>
    <add name="MyConnString" connectionString="server=XXXX;database=XXXX;uid=XXXX;password=XXXX;" 
    providerName="System.Data.SqlClient"/>
   </connectionStrings>
</configuration>

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)
            {
                BindDropDown();
            }
        }
        public void BindDropDown()
        {
            con = new SqlConnection(MyConnString);
            cmd = new SqlCommand("select Id,City from tblCity", con);
            cmd.CommandType = CommandType.Text;
            con.Open();
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
            sda.Fill(ds);
            ddlCity.DataSource = ds;
            ddlCity.DataTextField = "City";
            ddlCity.DataValueField = "Id";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem("--select--"));
        }

Output

Output will be shown as below.

Bind DropDownList control from DataBase in asp.net




blog comments powered by Disqus