SIGN UP MEMBER LOGIN:    
ARTICLE

Cascading DropDown With AJAX

Posted by Mahak Gupta Articles | AJAX in C# November 13, 2010
In this article we will see how to implement dropdown in ajax.
Reader Level:

Step 1: Create a table in database

create table test
(
state1 varchar(50),
city varchar(50)  

Step 2: In the .aspx Page

<select id="statelist" runat="server" onchange="showCity()" style="width: 160px">
    <option></option>
</select>
<asp:DropDownList ID="citylist" runat="server" Width="184px">
</asp:DropDownList>

Take statelist for State and citylist for City 

When you select any item from statelist the citylist will automatically fill because of ajax 

Step 3:  Write this in the <head> Part

<script language="JavaScript" type="text/javascript" >
    var xmlHttp
    var arr;
    function showCity() {
        xmlHttp = GetXmlHttpObject()
        var url = "Default.aspx"
        url = url + "?name=" + document.getElementById('statelist').value
        xmlHttp.onreadystatechange = stateChanged
        xmlHttp.open("GET", url, true)
        xmlHttp.send(null)
        return false;
    }
    function stateChanged() {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
            var str;
            str = xmlHttp.responseText;
            arr = str.split(",");
            var i;
            for (i = 0; i < arr.length; i++) {
                dd2 = document.getElementById("citylist")
                var theOption = new Option;
                theOption.text = arr[i];
                theOption.value = arr[i];
                dd2.options[i] = theOption;
            }
        }
    }
    function GetXmlHttpObject() {
        var objXMLHttp = null
        if (window.XMLHttpRequest) { 
            objXMLHttp = new XMLHttpRequest()
        }
        else if (window.ActiveXObject) {
            objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
        }
        return objXMLHttp
    }
</script>

Step 4:  In the .cs page

SqlConnection con = new SqlConnection("data source = MY\\SQLEXPRESS; initial catalog = try; integrated security=true");
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from test", con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        statelist.DataSource = dr;
        statelist.DataTextField = "state";
        statelist.DataBind();
        dr.Close();
        con.Close();
    }
    if (Request.QueryString["name"] != null)
    {
        string name = Request.QueryString["name"];
        Response.Clear();
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from test where state=@state", con);
        cmd.Parameters.AddWithValue("@state", name);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        string str = "";
        int a = 0;
        while (dr.Read())
        {
            if (a == 0)
                str += dr["city"].ToString();
            else
                str += "," + dr["city"].ToString();
            a++;
        }
        Response.Write(str);
        Response.End();
        con.Close();
    }
}

Login to add your contents and source code to this article
share this article :
post comment
 

Its working fine. Thanks

Posted by Satyapriya Nayak Dec 09, 2010
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor