Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET
Article

Binding dropdowns using Ajax

Rate me:
Please Sign up or sign in to vote.
2.71/5 (4 votes)
25 May 20071 min read 54.5K   620   20   4
How to populate a dropdown in another dropdown change

Introduction

This project contains multiple samples for Ajax, such as loading repeaters, binding dropdowns, getting usernames, passing user IDs, etc. Here I will be explaining how to bind a dropdown using Ajax in another dropdown change event. In this code section, I have copied the two types of models to bind the dropdown. One is in the Button Click event and the other one is in the Change event of the dropdown.

Using the code

Below is a brief description of how to use the article code, including the class names, methods, properties and any tricks or tips. First, create a DB class of nothing but the connection establishment. Then create the table that you want to bind with the dropdown list. Next, change the connection string in the Web.config file.

Bind the dropdown using the Ajax Click event connection string

JavaScript
<appSettings>
    <add key="ConnectionString" value=
        "Data Source=.\SQLEXPRESS;Integrated Security=yes;database=TAACS;"/>
</appSettings>

Register the page for Ajax

C#
AjaxPro.Utility.RegisterTypeForAjax(typeofSample1));
// Write the Ajax method to bind the drop down  
[AjaxPro.AjaxMethod]
public DataSet GetDataSet()
{
    string connectionString = 
        (string)ConfigurationManager.AppSettings["ConnectionString"];
    SqlConnection myConnection = new SqlConnection(connectionString);
    SqlDataAdapter ad = new SqlDataAdapter(
        "SELECT * FROM Tabs", myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "Tabs");
    return ds;
}

At the HTML design page, write the JavaScript to bind

C#
// your code is start here
<script language="JavaScript">
function GetDataSet() 
{
    Sample1.GetDataSet(callback);
}

function callback(res)
{
    var html = [];
    for(var i=0; i < res.value.Tables[0].Rows.length; i++)
    html[html.length] = 
        "<option>" + res.value.Tables[0].Rows[i].TabName + "</option>";
    document.getElementById("display").innerHTML = 
        "<select id=\"sel\">" + html.join("") + "</select>";
}
</script>

Use a System.Data.DataSet to fill a drop down box

Because you can return any object, it is possible to fill a dropdown box with only two lines. The list of countries will be fetched from the server after you have clicked on the link.

Method 1

Bind the dropdown via the dropdown change event:

C#
<script language="JavaScript">
function GetTabSet()
{
    var countryId = document.getElementById(
        "ddlList").value;// ddlList.options[ddlList.selectedIndex].value;
    MyAjaxSample.SampleforDatabind.GetTabSet(countryId, GetTabSet_CallBack);
}

function GetTabSet_CallBack(response)
{
    if (response.error != null)
    {
        alert(response.error); 
        return;
    }
    var states = response.value; 
    if (states == null || typeof(states) != "object")
    {
        return;
    }
    var statesList = document.getElementById("ddlItemList");
    statesList.options.length = 0; 
    for (var i = 0; i < response.value.Tables[0].Rows.length; ++i)
    {
        statesList.options[statesList.options.length] = 
            new Option(response.value.Tables[0].Rows[i].TabName);
    }
}
</script>

Now, load the data from the database using Ajax:

C#
In Code bihind 
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HTMLControls;
using Ganesh;
 
namespace MyAjaxSample
{
    public partial class SampleforDatabind : System.Web.UI.Page
    {
        public static string connectionString = 
            (string)ConfigurationManager.AppSettings["ConnectionString"];
        public DataSet ds = new DataSet();
        DBClass MyClass = new DBClass();
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(SampleforDatabind));
            if (!IsPostBack)
            {
                ddlList.DataSource = MyClass.GetDataSet("Select * from Users");
                ddlList.DataTextField = "UserName";
                ddlList.DataValueField = "UserID";
                ddlList.DataBind();
                ddlList.Items.Add("--Select table--");
                ddlList.SelectedIndex = ddlList.Items.Count - 1;
            }
        }

        [AjaxPro.AjaxMethod]
        public DataSet GetDataSet() 
        {
            SqlConnection myConnection = new SqlConnection(connectionString); 
            SqlDataAdapter ad = new SqlDataAdapter(
                "SELECT * FROM Tabs",myConnection);
            ad.Fill(ds, "Tabs");
            return ds;
        }

        [AjaxPro.AjaxMethod]
        public DataSet GetTabSet(int UserId)
       {
           SqlConnection myConnection = new SqlConnection(connectionString);
           SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM GetRoleTabs(
               " + UserId + ")", myConnection);
           ad.Fill(ds, "Tabs");
           return ds;
       }
    }
}

Method 2

Bind the dropdown in change event:

C#
<%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="~/Sample.aspx.cs" Inherits="MyAjaxSample.Sample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head>
<title>Sample Ajax Page</title>
<script language="JavaScript">
function GetUserName()
{
    var yourid = document.getElementById("txtuserId").value;
    MyAjaxSample.Sample.GetUserName(yourid,GetUserName_callback);
}
function GetUserName_callback(response)
{
    if (response != null && response.value != null)
    {
        var user = response.value;
        alert(user);
    }
}

// Get the User Permission tabs by passing User ID
function GetUserRole()
{
    var UID = document.getElementById("ddlUser").value;
    MyAjaxSample.Sample.GetUserRole(UID,GetUserRole_callback);
}

function GetUserRole_callback(response)
{
    if (response != null && response.value != null)
    {
        var usertab = response.value;
        alert(usertab);
    }
}

function GetRoleTabs()
{
    var UrID = document.getElementById("ddlUserList").value;
    MyAjaxSample.Sample.GetRoleTabs(UrID,GetRoleTabs_callback);
}

function GetRoleTabs_callback(res)
{
    var html = [];
    for(var i=0; i < res.value.Tables[0].Rows.length; i++)
    html[html.length] = "<option>" + 
        res.value.Tables[0].Rows[i].TabName + "</option>";
    document.getElementById("display").innerHTML = 
        "<select id=\"sel\">" + html.join("") + "</select>";
}

</script>
</head>

<body>
<form id="form1" runat="server" method="post">
<div style="text-align: center">
    <table id="TABLE1" border="1" cellpadding="0" cellspacing="0" >
        <tr>
            <td style="width: 100px; height: 22px;">
                <input id="btnUser" type="button" value="User" 
                    onclick="GetUserName()" />
            </td>
            <td style="width: 100px">
                <asp:DropDownList ID="ddlUser" OnChange="GetUserRole()" 
                    runat="server" Width="132px"></asp:DropDownList>
            </td>
            <td style="width: 100px">
                <asp:DropDownList ID="ddlUserList" OnChange="GetRoleTabs()" 
                    runat="server" Width="132px" style="position: static">
                 </asp:DropDownList>
            </td>
        </tr>
    </table>
</div> 
</form>
</body>
</html>

In code behind

C#
namespace MyAjaxSample
{ 
    public partial class Sample : System.Web.UI.Page
    {
        DBClass ObjDB = new DBClass();
        DataSet ObjDS = new DataSet();
        public SqlConnection ObjCon = 
            new SqlConnection(
            ConfigurationManager.AppSettings["ConnectionString"]);
        SqlDataReader ObjReader;
        SqlDataAdapter ObjAdapter;
        public string username,usertab;
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Sample)); // Step 3
            if (!IsPostBack)
            {
                BindDropDown();
            }
        }

        [AjaxPro.AjaxMethod()]
        public string GetUserName(int userID)
        {
            string strSelect = 
                "select * from Users where UserID='" + userID + "'";
            ObjReader = ObjDB.GetDataReader(strSelect);
            if(ObjReader.Read())
            {
                username = 
                    ObjReader["FName"].ToString()+
                    " "+ObjReader["LName"].ToString();
            }
            return username;
        }

    public void BindDropDown()
    {
        string strSelect = "Select * from Users";
        ObjDS = ObjDB.GetDataSet(strSelect);
        ddlUser.DataSource = ObjDS;
        ddlUser.DataTextField = "UserName";
        ddlUser.DataValueField = "UserID";
        ddlUser.DataBind();
        ddlUser.Items.Add("--Select table--");
        ddlUser.SelectedIndex = ddlUser.Items.Count - 1;
        ddlUserList.DataSource = ObjDS;
        ddlUserList.DataTextField = "UserName";
        ddlUserList.DataValueField = "UserID";
        ddlUserList.DataBind();
        ddlUserList.Items.Add("--Select table--");
        ddlUserList.SelectedIndex = ddlUserList.Items.Count - 1;
    }

    [AjaxPro.AjaxMethod()]
    public string GetUserRole(string userID)
    {
        string strSelectTab="select * from GetUserRole(" + userID + ")";
        ObjReader = ObjDB.GetDataReader(strSelectTab);
        if (ObjReader.Read())
        {
            usertab = ObjReader["RoleName"].ToString();
        }
    return usertab;
    }

    [AjaxPro.AjaxMethod()] 
    public DataSet GetRoleTabs(string userID)
    {
        string strSelectTab = "Select * from GetRoleTabs(" + userID + ")";
        ObjAdapter = new SqlDataAdapter(strSelectTab,ObjCon);
        ObjAdapter.Fill(ObjDS,"Tabs");
        return ObjDS;
    }
}

The above code has been written in C#. Here, I have copied both the HTML page and the code behind file code. Remember to set the Language of your code snippet using the Language dropdown. Use the "var" button to to wrap Variable or class names in <code> tags like this.

History

  • 25 May, 2007 - Original version posted

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
I'm Ganesan.S,
Software Engineer
Involved in developing MS applications for last 7 Yrs in VB,VB.NET,ASP.NET,Java Script and C#.NET lately into EPiServer and Ajax.

Comments and Discussions

 
QuestionDatabase script ? Pin
Jaydev Jangid17-Jan-12 23:37
Jaydev Jangid17-Jan-12 23:37 
Generalradio button group - web control (postback) caused combo-box not to remember it's value via ajaxpro Pin
fletchsod27-Mar-08 11:54
fletchsod27-Mar-08 11:54 
GeneralKeep it up Gane.. Pin
2bSmrt25-May-07 0:38
2bSmrt25-May-07 0:38 
GeneralRe: Keep it up Gane.. Pin
King Shez2-Jun-07 0:11
King Shez2-Jun-07 0:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.