Friday, September 6, 2013

CascadingDropDown List in Asp.Net and SQL Server

Hello friends,
Now I am going to tell you that how we can use Ajax cascading dropdown list using web services in asp.net. I will be explaining all steps one by one.
Step 1: First of all I will be design database and create table and store procedure one by one.
CREATE DATABASE testdata
Now create table State and City-
CREATE TABLE [dbo].[State](
      [stateid] [int] IDENTITY(1,1) NOT NULL,
      [statename] [nvarchar](100) NULL,
 CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED
(
      [stateid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[City](
      [Cityid] [int] IDENTITY(1,1) NOT NULL,
      [Stateid] [int] NULL,
      [Cityname] [nvarchar](100) NULL,
 CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
      [Cityid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 2: Start Visual Studio, And create New Website. Now  click on top of root and click on Add New Item ->WebService, this file will be create with name of WebService.asmx in root and other is in App_code with name of WebService.cs like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService2
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
   
}

Now we will be write code for select state and city from the database like as-
using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Configuration;
using System.Data;


/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

   SqlConnection cmd = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
     
    [WebMethod]
    public CascadingDropDownNameValue[] Bindstate(string knownCategoryValues, string category)
    {
        cmd.Open();
        SqlCommand cmdstate = new SqlCommand("select  * from State", cmd);
        SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
        cmdstate.ExecuteNonQuery();
        DataSet dscountry = new DataSet();
        dastate.Fill(dscountry);
        cmd.Close();
        List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dscountry.Tables[0].Rows)
        {
            string StateID = dtrow["Stateid"].ToString();
            string StateName = dtrow["Statename"].ToString();
            statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
        }
        return statedetails.ToArray();
    }
    [WebMethod]
    public CascadingDropDownNameValue[] Bindcity(string knownCategoryValues, string category)
    {
        int Stateid;
        StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        Stateid = Convert.ToInt32(statedetails["State"]);
        cmd.Open();
        SqlCommand cmdregion = new SqlCommand("select  * from City where Stateid=@Stateid ", cmd);
        cmdregion.Parameters.AddWithValue("@Stateid", Stateid);
        cmdregion.ExecuteNonQuery();
        SqlDataAdapter daregion = new SqlDataAdapter(cmdregion);
        DataSet dsregion = new DataSet();
        daregion.Fill(dsregion);
        cmd.Close();
        List<CascadingDropDownNameValue> regiondetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtregionrow in dsregion.Tables[0].Rows)
        {
            string regionID = dtregionrow["CityId"].ToString();
            string regionname = dtregionrow["Cityname"].ToString();
            regiondetails.Add(new CascadingDropDownNameValue(regionname, regionID));

        }
        return regiondetails.ToArray();
    }
   
}

Step 3: Now we will be create a page default.aspx, and write code like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>


<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager><asp:UpdatePanel ID="panel1" runat="server"><ContentTemplate>
    <fieldset style=" width:500px"><legend>Cascading Dropdownlist</legend>
    <table><tr><td>Select State</td><td><asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList>
        <asp:CascadingDropDown ID="CascadingDropDown1" runat="server" Category="State" TargetControlID="ddlstate" PromptText="Select state"  LoadingText="Loading state.." ServiceMethod="Bindstate" ServicePath="WebService.asmx">
</asp:CascadingDropDown>
     <%--   <asp:CascadingDropDown ID="CascadingDropDown11" runat="server" Category="State" TargetControlID="ddlstate" LoadingText="Loading state......." PromptText="---Select State---" ServiceMethod="Bindstate" ServicePath="WebService.asmx">
        </asp:CascadingDropDown>--%>
    </td></tr>
   <tr><td>Select City</td><td> <asp:DropDownList ID="ddlcity" runat="server"></asp:DropDownList><asp:CascadingDropDown ID="CascadingDropDown2" runat="server" ParentControlID="ddlstate" TargetControlID="ddlcity" LoadingText="Loading City......." PromptText="---Select city---" Category="City" ServiceMethod="Bindcity" ServicePath="WebService.asmx">
        </asp:CascadingDropDown></td></tr>
  
   </table></fieldset>
  </ContentTemplate></asp:UpdatePanel>
  
    </form>
</body>
</html>

After debugging the website our page will be display like this.




 Now download source code for this project from here 


1 comment: