Click here to Skip to main content
15,880,405 members
Articles / Web Development / ASP.NET

Dropdown Binding Using AJAX

Rate me:
Please Sign up or sign in to vote.
1.48/5 (9 votes)
24 May 2007CPOL 38.7K   211   21   2
Binding a dropdown list control in a dropdown list's change event using AJAX.

Introduction

This article tells you how to bind a dropdown list in another dropdown list's change event using AJAX.

Using the code

Download the source file from above. Create the tables which I have mentioned in the article, and create the required functions in your database. Update the name of the database in your web.config file.

In the code-behind:

C#
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;
        }
    }
}

In the HTML side:

JavaScript
<script language="javascript">
function BindDatatoTable()
{
     MyAjaxSample.SampleforDatabind.GetDataSet(BindDatatoTable_callback);
}
function BindDatatoTable_callback(responce)
{
    if(responce.error == null) 
    { 
        var ds = responce.value;
        if(ds!= null && typeof(ds) == "object" && ds.Tables!=null)
        {
            var s = new Array();
            s[s.length] = "<table border = 1 cellpadding=0 cellspacing=0 bordercolor=blue >";
            for(var i=0;i<ds.Tables[0].Rows.length;i++)
            {
                s[s.length] = "<tr>";
                s[s.length] = "<td>" + ds.Tables[0].Rows[i].TabID + "</td>";
                s[s.length] = "<td>" + ds.Tables[0].Rows[i].TabName + "</td>";
                s[s.length] = "<td>" + ds.Tables[0].Rows[i].Remarks + "</td>";
                s[s.length] = "</tr>";
            }
            s[s.length] = "</table>";
            document.getElementById("Display1").innerHTML = s.join("");
        } 
    } 
}
function GetTabSet()
{
    // ddlList.options[ddlList.selectedIndex].value;
    var countryId = document.getElementById("ddlList").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,
           response.value.Tables[0].Rows[i].TabID);
    }
}
</script>

//See the Change event call here

<div>
<input id="btnLoad" type="button" 
   value="Load Data" onclick="BindDatatoTable();" /></div>
<span id="Display1" 
   title="Loading the Data from the Database using Ajax">
   Loading the Data from the Database using Ajax</span>
<br /><p>Menu</p>
<asp:DropDownList ID="ddlList" onchange="GetTabSet()" 
         runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddlItemList" runat="server" ></asp:DropDownList>
</div>

Here are the tables used in this example:

SQL
CREATE TABLE Tabs (TabID varchar(50) ,TabName varchar(50),Remarks varchar(50) )
Create Table RolePermission (PermissionID varchar(50),
             RoleID varchar(50),TabID varchar(50),Show Varchar(50))
Create Table UserRole (UserRoleID Varchar(50),UserID Varchar(50),RoleID Varchar(50))
Create Table Roles (RoleID Varchar(50),RoleName Varchar(50),Remarks Varchar(50))
Create Table Users (UserID varchar(50),Username varchar(50),Password(10))

Here is the SQL function used to get the tabs:

SQL
ALTER FUNCTION [dbo].[GetRoleTabs] 
( 
    @UserID varchar(20)
)
RETURNS TABLE 
AS
RETURN 
(
    Select A.TabID,A.TabName from Tabs A,RolePermission B, 
      UserRole C where A.TabID=B.TabID and b.RoleID=C.RoleID AND B.Show=1
    AND C.UserID=@UserID
)

Create the above tables and function in a database, and enter some values in those tables.

Note: In all the tables, the first column is considered the Primary key. Don't forget to change the name of the database in the web.config file.

Points of Interest

You can easily bind a dropdown list in another dropdown list's change event using AJAX by following this sample. Moreover, I have included another functionality in the Click event so you can bind a Repeater without page post back.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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

 
QuestionWhat the big deal..? Pin
ucin.shahab3-Jun-07 22:51
ucin.shahab3-Jun-07 22:51 
Sorry, but I have seen this kind of article a lot. How can you use DataSet to bind to DropDown control that only need 2 pair of value instead a copy of table from database. Confused | :confused:
Generalkeep it up.. Pin
2bSmrt25-May-07 0:40
2bSmrt25-May-07 0:40 

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.