Saturday 26 January 2013

Working with ajax CascadingDropDown with C#

.aspx page

<table>

<tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select Country&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_countryPermenent" runat="server" Width="250px" DataTextField="countryName" DataValueField="countryID">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_countryPermenent" runat="server" Category="Country"
                                                TargetControlID="ddl_countryPermenent" PromptText="Select Country" LoadingText="Loading country..."
                                                ServiceMethod="BindCountryDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select State&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_statePermenent" runat="server" Width="250px">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_statePermenent" runat="server" Category="State" ParentControlID="ddl_countryPermenent"
                                                TargetControlID="ddl_statePermenent" PromptText="Select State" LoadingText="Loading state..."
                                                ServiceMethod="BindStateDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
</table>


Now make one class file and create a method which calls store procedure


public DataSet RetiveCountry()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SELECTCOUNTRY4DDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }




public DataSet RetiveState(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("SSP_FETCHSTATEDDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }


Now make Http Handler file (.asmx)




using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;



/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class WebService : System.Web.Services.WebService {

    public WebService () {

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

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
 
    //------ METHOD TO POPULATE COUNTRY -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues, string category)
    {
        ManageState obj = new ManageState();

        System.Data.DataSet ds = obj.RetiveCountry();

        System.Collections.Generic.List<CascadingDropDownNameValue> CountryDetails = new System.Collections.Generic.List<CascadingDropDownNameValue>();
        foreach (System.Data.DataRow dtrow in ds.Tables[0].Rows)
        {
            string CountryID = dtrow["countryID"].ToString();
            string CountryName = dtrow["countryName"].ToString();
            CountryDetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
        }
        obj = null;
        return CountryDetails.ToArray();
    }

    //------ METHOD TO POPULATE STATE -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues, string category)
    {
        int countryID;
        //This method will return a StringDictionary containing the name/value pairs of the currently selected values
        StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        countryID = Convert.ToInt32(countrydetails["Country"]);
     
        //concountry.Open();
        //SqlCommand cmdstate = new SqlCommand("select * from StateTable where CountryID=@CountryID", concountry);
        //cmdstate.Parameters.AddWithValue("@CountryID", countryID);
        //cmdstate.ExecuteNonQuery();
        //SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);

        ManageState obj = new ManageState();

        DataSet dsstate = obj.RetiveState(countryID);
     
        //dastate.Fill(dsstate);
        //concountry.Close();

        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsstate.Tables[0].Rows)
        {
            string StateID = dtrow["stateId"].ToString();
            string StateName = dtrow["stateName"].ToString();
            statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
        }
        return statedetails.ToArray();
    }
}


Now access the dropdownlist value from code behind ( C# )



string countryP = ddl_countryPermenent.SelectedItem.Text;
        string stateP = ddl_statePermenent.SelectedItem.Text;


if (!string.IsNullOrEmpty(countryP)
{
            if (!string.IsNullOrEmpty(stateP))
           {
                        int id_country = Convert.ToInt32(ddl_countryPermenent.SelectedValue);
                        int id_state = Convert.ToInt32(ddl_statePermenent.SelectedValue);
            }
}


        string country_C = ddl_countryCurrent.SelectedItem.Text;
        string state_C = ddl_stateCurrent.SelectedItem.Text;


        int countryC = 0;
        int stateC = 0;
        if (!string.IsNullOrEmpty(country_C))
        {
            countryC = Convert.ToInt32(ddl_countryCurrent.SelectedValue);

            if (!string.IsNullOrEmpty(country_C))
            {
                stateC = Convert.ToInt32(ddl_stateCurrent.SelectedValue);
            }
        }



Now if you want to assign value from code behind then 


ccd_countryPermenent.SelectedValue = "your value from database OR your static value";
ccd_statePermenent.SelectedValue = "your value from database OR your static value";



Enjoy............ Best of luck

No comments:

Post a Comment