Implement Cascading DropDownList in DataGrid using jQuery AJAX and Web service in ASP.Net

Amitabha
 
on Feb 02, 2021 09:20 PM
Sample_146484.zip
1261 Views

Dear Sir

How to consume this Webservice in my Datagrid using ajax.

    [WebMethod]
    public DataSet GetStation()
    {
        str = "SELECT STN_NAME,STN_CODE FROM CM_STATION_MASTER WHERE DIV_CODE='" + Session["DivCode"].ToString() + "' AND BRANCH_CODE='" + ddlBranch.SelectedValue + "'";
        DataSet ds = new DataSet();
        OracleDataAdapter da;
        da = new OracleDataAdapter(str,oper.ConnectionString);
        da.Fill(ds);
        return ds;
    }

 

<script>
    $("[id*=ddlFromLocationType]").change(function () {
        try {
            var row = $(this).closest("tr");
            var value = $(this).val();
            if (value == "STN") {

                var Statn = document.getElementById("[id*=ddlFromStn]");
                toastr.info('Station Wise Rate Applicable');
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "CustomerMaster.aspx/GetFromLocation",
                    data: "{}",
                    dataType: "json",
                    success: function (Result)
                    {
                        Result = Result.d;
                        var data = [];
                       
                        for (var i = 0; i < Result.length; i++)
                        {
                            var selectOption = $(document.createElement('option'));
                            row.find("[id*=ddlFromBranch]").append(selectOption.val(Result[i].StnCode).html(Result[i].StnName));
                        }
                        alert(data);
                        
                    },
                    error: function (Result)
                    {
                        alert(Result);
                    }
                });
            }
            if (value == "CITY")
            {
                toastr.info('City Wise Rate Applicable');
                row.find("[id*=txtFromBranch]").hide();
                row.find("[id*=ddlFromBranch]").val('default').selectpicker("refresh");
            }
            if (value == "STATE") {
                toastr.info('State Wise Rate Applicable');
                row.find("[id*=txtFromBranch]").hide();
                row.find("[id*=ddlFromBranch]").val($('[id*=ddlToState]').val());
                row.find("[id*=ddlFromBranch]").val('default').selectpicker("refresh");
            }
            if (value == "REGN") {
                toastr.info('Region Wise Rate Applicable');
                row.find("[id*=txtFromBranch]").hide();
                row.find("[id*=ddlFromBranch]").val($('[id*=ddlToRegn]').val());
                row.find("[id*=ddlFromBranch]").val('default').selectpicker("refresh");
            }
        }
        catch (e) {
            alert(e);
        }
    });
</script>

 

                    <asp:DataGrid ID="gridRate" CssClass="table table-striped table-bordered" runat="server"
                        AutoGenerateColumns="false" CellPadding="3" Width="100%" HeaderStyle-BackColor="#0099cc" HeaderStyle-ForeColor="White"
                        OnItemDataBound="gridRate_ItemDataBound"  AllowPaging="true"
                        OnPageIndexChanged="gridRate_PageIndexChanged" PageSize="13"
                        onitemcreated="gridRate_ItemCreated">
                      
                        <PagerStyle Mode="NumericPages" PageButtonCount="30" BackColor="AliceBlue" CssClass="GridPage" />
                        <Columns>
                            <asp:TemplateColumn HeaderText="From Division">
                                <ItemTemplate>
                                    <asp:DropDownList ID="ddlFromDivision"  runat="server" CssClass="form-control selectpicker"></asp:DropDownList>                                       
                                </ItemTemplate>
                            </asp:TemplateColumn>
                            <asp:TemplateColumn HeaderText="From Location Type">
                                <ItemTemplate>
                                    <asp:DropDownList ID="ddlFromLocationType"  runat="server"
                                         
                                        CssClass="form-control selectpicker"></asp:DropDownList>                                       
                                    <input type="hidden" id="hdnFromLocationType" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "FROM_LOCATION_TYPE") %>' />
                                </ItemTemplate>
                            </asp:TemplateColumn>
                            <asp:TemplateColumn HeaderText="From Location">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtFromBranch"  runat="server" MaxLength="4" CssClass="form-control hidden" Width="50px" Text='<%# DataBinder.Eval(Container.DataItem, "FROM_LOCATION") %>'></asp:TextBox>               
                                      <asp:DropDownList ID="ddlFromBranch"  runat="server" CssClass="form-control selectpicker"></asp:DropDownList>
                                    <input type="hidden" id="hdnFromBranch" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "FROM_LOCATION") %>' />
                                </ItemTemplate>
                            </asp:TemplateColumn>                            
                            <asp:BoundColumn DataField="SR_NO" HeaderText="SrNo" Visible="False"></asp:BoundColumn>
                        </Columns>                       
                    </asp:DataGrid>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Feb 03, 2021 06:30 AM

Hi Amitabha,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:DataGrid ID="gridCustomers" CssClass="table table-striped table-bordered" runat="server" AutoGenerateColumns="false"
    CellPadding="3" Width="100%" HeaderStyle-BackColor="#0099cc" HeaderStyle-ForeColor="White" AllowPaging="true" PageSize="13">
    <PagerStyle Mode="NumericPages" PageButtonCount="30" BackColor="AliceBlue" CssClass="GridPage" />
    <Columns>
        <asp:BoundColumn HeaderText="Name" DataField="Name" />
        <asp:TemplateColumn HeaderText="Country">
            <ItemTemplate>
                <asp:DropDownList ID="ddlCountries" runat="server">
                    <asp:ListItem Text="Select" Value="0" Selected="True"></asp:ListItem>
                    <asp:ListItem Text="USA" Value="USA"></asp:ListItem>
                    <asp:ListItem Text="UK" Value="UK"></asp:ListItem>
                    <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="City">
            <ItemTemplate>
                <asp:DropDownList ID="ddlCities" runat="server">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=ddlCountries]").change(function () {
            try {
                var row = $(this).closest("tr");
                var value = $(this).find('option:selected').val();
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Service.asmx/GetCities",
                    data: "{country:'" + value + "'}",
                    dataType: "json",
                    success: function (Result) {
                        Result = Result.d;
                        var data = [];
                        for (var i = 0; i < Result.length; i++) {
                            var selectOption = $(document.createElement('option'));
                            row.find("[id*=ddlCities]").append(selectOption.val(Result[i].Value).html(Result[i].Text));
                        }
                    },
                    error: function (Result) {
                        alert(Result);
                    }
                });
            }
            catch (e) {
                alert(e);
            }
        });
    });
</script>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3]
        {
            new DataColumn("Id"),
            new DataColumn("Name"),
            new DataColumn("Country")
        });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        gridCustomers.DataSource = dt;
        gridCustomers.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {
                            New DataColumn("Id"),
                            New DataColumn("Name"),
                            New DataColumn("Country")})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        gridCustomers.DataSource = dt
        gridCustomers.DataBind()
    End If
End Sub

WebService

C#

[WebMethod]
public List<ListItem> GetCities(string country)
{
    List<ListItem> items = new List<ListItem>();
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT Distinct City FROM Customers WHERE Country = @Country";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@Country", country);
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            items.Add(new ListItem { Text = sdr["City"].ToString(), Value = sdr["City"].ToString() });
        }
        items.Insert(0, new ListItem { Text = "Select", Value = "0" });
        con.Close();
    }

    return items;
}

VB.Net

<WebMethod>
Public Function GetCities(ByVal country As String) As List(Of ListItem)
    Dim items As List(Of ListItem) = New List(Of ListItem)()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT Distinct City FROM Customers WHERE Country = @Country"
    Using con As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand = New SqlCommand(query, con)
        cmd.Parameters.AddWithValue("@Country", country)
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        While sdr.Read()
            items.Add(New ListItem With {.Text = sdr("City").ToString(), .Value = sdr("City").ToString()})
        End While
        items.Insert(0, New ListItem With {.Text = "Select", .Value = "0"})
        con.Close()
    End Using

    Return items
End Function

Screenshot