Home > ASP.Net, Javascript > Bind HTML DropdownList from Database

Bind HTML DropdownList from Database

Hi all,

try this example to Bind HTML DropdownList from Database using ADO.NET

In this example i will use Northwind database

1) Open VS2008 and create a new website and add web page

2) From Toolbox drag and drop HTML Select and HTML Button control

<head runat="server">
 <script type="text/javascript">
 function getValues() {
 var opt = document.getElementById('Select1');
 var selected = "";
 var Text = "";
 var index = 0;
 for (var intLoop = 0; intLoop < opt.length; intLoop++) {
 if (opt[intLoop].selected) {
 selected += opt[intLoop].value + ',';
 Text += opt[intLoop].text + ',';
 alert('Selected Value '+selected+' --- selected Text '+Text);
 <form id="form1" runat="server">
 <select id="Select1" multiple="multiple">
 <input id="Button1" type="button" value="Get Values" onclick="getValues();" />

and in code behind :-

private void Bind()
 string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
 SqlConnection connection = new SqlConnection(constr);
 string sql1 = "select * from Categories";
 SqlDataAdapter sda1 = new SqlDataAdapter(sql1, connection);
 DataSet ds1 = new DataSet();
 sda1.Fill(ds1, "Categories");

StringBuilder str = new StringBuilder();
 str.Append("<script language=javascript>");
 int i;
 for (i = 0; i < ds1.Tables["Categories"].Rows.Count; i++)
 string id = ds1.Tables["Categories"].Rows[i]["CategoryName"].ToString().Trim();
 string name = ds1.Tables["Categories"].Rows[i]["CategoryID"].ToString().Trim();
 str.Append("document.getElementById(\"Select1\").options.add(new Option(\"" + id + "\", \"" + name + "\"));");
 Page.ClientScript.RegisterStartupScript(this.GetType(), "clientscript", str.ToString());

protected void Page_Load(object sender, EventArgs e)
 if (!IsPostBack)

Don’t forget to use the following Namespaces

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

3) In Web.Config file add ConnectionString

 <add name="conn" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"
 providerName="System.Data.SqlClient" />

Hope this helps

Good Luck

Categories: ASP.Net, Javascript
  1. hraqd
    April 17, 2012 at 10:23 am

    not runnable

  2. September 15, 2013 at 11:19 am

    LoOks Very Nice..
    I am gOing to Try it 😉

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: