Populate DropDownList and set selected value on Edit Button click using jQuery Ajax in ASP.Net

Last Reply 5 days ago By kalpesh

Posted 6 days ago
i have a senario, suppose that u saved some records from your submit form and you save name , surname, country, state and city,, when you call back this records how to show on dropdownlist recorded country, state and city
You are viewing reply posted by: kalpesh 5 days ago.
Posted 5 days ago Modified on 5 days ago

Refer the below Sample code for you reference.

SQL

/* Table Script */
CREATE TABLE [Country]
(
	[CountryID] INT NOT NULL,
	[CountryName] VARCHAR(50) NOT NULL
) 
GO

CREATE TABLE [State]
(
	[StateID] INT NOT NULL,
	[CountryID] INT NULL,
	[StateName] VARCHAR(50) NULL
)
GO

CREATE TABLE [City]
(
	[CityID] [int] NOT NULL,
	[StateID] [int] NOT NULL,
	[CityName] VARCHAR(50) NOT NULL
)
GO

CREATE TABLE [UserInfomation]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NULL,
    [Surname] [varchar](100) NULL,
    [CountryId] [int] NULL,
    [StateId] [int] NULL,
    [CityId] [int] NULL 
) 
GO

/* Insert Script */
INSERT INTO [Country] ([CountryID],[CountryName])
SELECT  1,'India'
UNION ALL
SELECT	2,'Australia'
UNION ALL
SELECT	3,'USA'
UNION ALL
SELECT	4,'UK'
UNION ALL
SELECT	5,'Canada'
GO

INSERT INTO[State](StateID,CountryID,StateName)
SELECT 1,1,'Maharashtra'
UNION ALL
SELECT 2,1,'Gujarat'
UNION ALL
SELECT 3,1,'Uttar Pardesh'
UNION ALL
SELECT 4,2,'Sydny'
UNION ALL
SELECT 5,2,'Perth'
GO

INSERT INTO [City] (CityID,StateID,CityName)
SELECT 1,1,'Mumbai'
UNION ALL
SELECT 2,1,'Pune'
UNION ALL
SELECT 3,1,'Nagpur'
UNION ALL
SELECT 4,2,'Ahemadabad'
UNION ALL
SELECT 5,2,'Surat'
UNION ALL
SELECT 6,2,'Rajkot'
GO

/* Stored Procedure*/
CREATE PROCEDURE [GetUsersDetails]
AS
BEGIN
SELECT Id
	   ,Name
	   ,SurName
	   ,CountryId
	   ,(Select CountryName From Country C WHERE UI.CountryId =  C.CountryId) CountryName
	   ,StateId
	   ,(Select StateName From State S WHERE UI.StateId =  S.StateId) StateName
	   ,CityId
	   ,(Select CityName From City CT WHERE UI.CityId =  CT.CityId) CityName
FROM UserInfomation UI
END
GO

 HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS"
    EnableEventValidation="false" %>

<!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 runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            GetCountries();
            $("[id*=ddlCountries]").change(function () {
                $("[id*=ddStates]").attr("disabled", "disabled");
                if ($(this).val() == "0") {
                    $("[id*=ddStates]").empty().append('<option selected="selected" value="0">Please select</option>');
                }
                else {
                    $("[id*=hfContryId").val($(this).val());
                    GetStates($(this).val());
                }
            });

            $("[id*=ddStates]").change(function () {
                $("[id*=ddlCities]").attr("disabled", "disabled");
                if ($(this).val() == "0") {
                    $("[id*=ddlCities]").empty().append('<option selected="selected" value="0">Please select</option>');
                }
                else {
                    $("[id*=hfStateId").val($(this).val());
                    GetCities($(this).val());
                }
            });

            $("[id*=ddlCities]").change(function () {
                $("[id*=hfCityId").val($(this).val());
            });

            /*On Edit click it will Populate the Details on Same Form*/
            $("[id*=lnkEdit").click(function () {
                $("[id*=hfMode]").val("Update");
                $("[id*=btnSubmit]").val("Update");
                var row = $(this).closest("tr");
                var name = row.find("[id*=lblName]")[0].innerText;
                var surName = row.find("[id*=lblSurname]")[0].innerText;
                var country = row.find("[id*=hfCountryValue]").val();
                var state = row.find("[id*=hfStateValue]").val();
                var city = row.find("[id*=hfCityValue]").val();
                var id = row.find("[id*=hfUserId]").val();
                $("[id*=hfContryId]").val(country);
                $("[id*=hfStateId]").val(state);
                $("[id*=hfCityId]").val(city);
                $("[id*=txtName]").val(name);
                $("[id*=txtSurName]").val(surName);
                $("[id*=hfId]").val(id);
                GetStates(country);
                GetCities(state);

                setTimeout(function () {
                    SetdropdownsValue();
                }, 1000);

                return false;
            });
        });

        /* Function to Populate the Country Dropdown*/
        function GetCountries() {
            $("[id*=ddlCountries]").removeAttr("disabled");
            $("[id*=ddStates]").attr("disabled", "disabled");
            $("[id*=ddStates]").empty().append('<option selected="selected" value="0">Please select</option>');
            $("[id*=ddlCities]").attr("disabled", "disabled");
            $("[id*=ddlCities]").empty().append('<option selected="selected" value="0">Please select</option>');
            $.ajax({
                type: "POST",
                url: "477414.aspx/GetCountries",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var ddlCountries = $("[id*=ddlCountries]");
                    ddlCountries.empty().append('<option value="0">Please select</option>');
                    $.each(r.d, function () {
                        ddlCountries.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        }

        /* Function to Populate the State Dropdown*/
        function GetStates(countryId) {
            $("[id*=ddStates]").removeAttr("disabled");
            $.ajax({
                type: "POST",
                url: "477414.aspx/GetStates",
                data: '{"countryId": "' + countryId + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var ddStates = $("[id*=ddStates]");
                    ddStates.empty().append('<option value="0">Please select</option>');
                    $.each(r.d, function () {
                        ddStates.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });

        }

        /* Function to Populate the City Dropdown*/
        function GetCities(stateId) {
            $("[id*=ddlCities]").removeAttr("disabled");
            $.ajax({
                type: "POST",
                url: "477414.aspx/GetCities",
                data: '{"stateId": "' + stateId + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var ddlCities = $("[id*=ddlCities]");
                    ddlCities.empty().append('<option value="0">Please select</option>');
                    $.each(r.d, function () {
                        ddlCities.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        }

        /* Function to sets the dropdown values*/
        function SetdropdownsValue() {
            if ($("[id*=hfContryId]").val().trim() != "") {
                $("[id*=ddlCountries] option").each(function () {
                    if ($(this).val() == $("[id*=hfContryId]").val()) {
                        $(this).attr('selected', 'selected');
                    }
                });
            }
            if ($("[id*=hfStateId]").val().trim() != "") {
                $("[id*=ddStates] option").each(function () {
                    if ($(this).val() == $("[id*=hfStateId]").val()) {
                        $(this).attr('selected', 'selected');
                    }
                });
            }

            if ($("[id*=hfCityId]").val().trim() != "") {
                $("[id*=ddlCities] option").each(function () {
                    if ($(this).val() == $("[id*=hfCityId]").val()) {
                        $(this).attr('selected', 'selected');
                    }
                });
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Name :&nbsp;
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"> </asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Surname :&nbsp;
                </td>
                <td>
                    <asp:TextBox ID="txtSurName" runat="server"> </asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Country :&nbsp;
                </td>
                <td>
                    <asp:DropDownList ID="ddlCountries" runat="server">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    State :&nbsp;
                </td>
                <td>
                    <asp:DropDownList ID="ddStates" runat="server">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    City :&nbsp;
                </td>
                <td>
                    <asp:DropDownList ID="ddlCities" runat="server">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="Submit" />
                    <asp:Button ID="brnCancel" runat="server" Text="Cancel" OnClick="Cancel" />
                    <asp:HiddenField ID="hfContryId" runat="server" Value="" />
                    <asp:HiddenField ID="hfStateId" runat="server" Value="" />
                    <asp:HiddenField ID="hfCityId" runat="server" Value="" />
                    <asp:HiddenField ID="hfMode" Value="Save" runat="server" />
                    <asp:HiddenField ID="hfId" Value="" runat="server" />
                </td>
            </tr>
        </table> 
        <br />
        <br />
        <b>Users Details</b><br /><br />
        <asp:GridView ID="gvUserDetails" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SurName">
                    <ItemTemplate>
                        <asp:Label ID="lblSurname" runat="server" Text='<%# Eval("SurName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("CountryName") %>'></asp:Label>
                        <asp:HiddenField ID="hfCountryValue" runat="server" Value='<%# Eval("CountryId") %>' />
                    </ItemTemplate>
                </asp:TemplateField >
                <asp:TemplateField HeaderText="State">
                    <ItemTemplate>
                        <asp:Label ID="lblState" runat="server" Text='<%# Eval("StateName") %>'></asp:Label>
                        <asp:HiddenField ID="hfStateValue" runat="server" Value='<%# Eval("StateId") %>' />
                    </ItemTemplate>
                </asp:TemplateField >
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("CityName") %>'></asp:Label>
                        <asp:HiddenField ID="hfCityValue" runat="server" Value='<%# Eval("CityId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server">Edit</asp:LinkButton>
                        <asp:HiddenField ID="hfUserId" runat="server" Value='<%# Eval("Id") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        BindUserDetails();
    }
}

protected void Submit(object sender, EventArgs e)
{
    string constring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
    SqlConnection con = new SqlConnection(constring);
    string query = "";
    if (hfMode.Value == "Save")
    {
        query = "insert into UserInfomation (Name,SurName,CountryId,StateId,CityId) values (@Name,@SurName ,@CountryId  ,@StateId ,@CityId)";
    }
    else
    {
        query = " Update UserInfomation Set Name =@Name ,SurName = @SurName ,CountryId = @CountryId , StateId = @StateId ,CityId = @CityId Where id = @id";
    }
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    if (hfMode.Value == "Update")
    {
        cmd.Parameters.AddWithValue("@Id", SqlDbType.VarChar).Value = Convert.ToInt32(hfId.Value);
    }
    cmd.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = txtName.Text;
    cmd.Parameters.AddWithValue("@SurName", SqlDbType.VarChar).Value = txtSurName.Text;
    cmd.Parameters.AddWithValue("@CountryId", SqlDbType.Int).Value = Convert.ToInt32(hfContryId.Value);
    cmd.Parameters.AddWithValue("@StateId", SqlDbType.Int).Value = Convert.ToInt32(hfStateId.Value);
    cmd.Parameters.AddWithValue("@CityId", SqlDbType.Int).Value = Convert.ToInt32(hfCityId.Value);
    cmd.ExecuteNonQuery();
    con.Close();
    BindUserDetails();
    ClearControls();
}

protected void Cancel(object sender, EventArgs e)
{
    this.Response.Redirect(Request.Url.AbsoluteUri);
}

private void ClearControls()
{
    txtName.Text = "";
    txtSurName.Text = "";
    hfContryId.Value = "";
    hfStateId.Value = "";
    hfCityId.Value = "";
    hfMode.Value = "Save";
    hfId.Value = "";
    btnSubmit.Text = "Save";
}

private void BindUserDetails()
{
    string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("GetUsersDetails"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            gvUserDetails.DataSource = dt;
            gvUserDetails.DataBind();
        }
    }
}

[WebMethod]
public static List<ListItem> GetCountries()
{
    string query = "SELECT CountryID,CountryName FROM Country";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> cities = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    cities.Add(new ListItem
                    {
                        Value = sdr["CountryID"].ToString(),
                        Text = sdr["CountryName"].ToString()
                    });
                }
            }
            con.Close();
            return cities;
        }
    }
}
[WebMethod]
public static List<ListItem> GetStates(int countryId)
{
    string query = "SELECT StateID,StateName FROM State where CountryID = @CountryID";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> states = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@CountryID", countryId);
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    states.Add(new ListItem
                    {
                        Value = sdr["StateID"].ToString(),
                        Text = sdr["StateName"].ToString()
                    });
                }
            }
            con.Close();
            return states;
        }
    }
}

[WebMethod]
public static List<ListItem> GetCities(int stateId)
{
    string query = "SELECT  CityID,CityName FROM City where StateID = @StateID";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> cities = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@StateID", stateId);
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    cities.Add(new ListItem
                    {
                        Value = sdr["CityID"].ToString(),
                        Text = sdr["CityName"].ToString()
                    });
                }
            }
            con.Close();
            return cities;
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindUserDetails()
    End If
End Sub

Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
    Dim constring As String = ConfigurationManager.ConnectionStrings("ConStr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constring)
    Dim query As String = ""
    If hfMode.Value = "Save" Then
        query = "insert into UserInfomation (Name,SurName,CountryId,StateId,CityId) values (@Name,@SurName ,@CountryId  ,@StateId ,@CityId)"
    Else
        query = " Update UserInfomation Set Name =@Name ,SurName = @SurName ,CountryId = @CountryId , StateId = @StateId ,CityId = @CityId Where id = @id"
    End If

    Dim cmd As SqlCommand = New SqlCommand(query, con)
    cmd.CommandType = CommandType.Text
    con.Open()
    If hfMode.Value = "Update" Then
        cmd.Parameters.AddWithValue("@Id", SqlDbType.VarChar).Value = Convert.ToInt32(hfId.Value)
    End If

    cmd.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = txtName.Text
    cmd.Parameters.AddWithValue("@SurName", SqlDbType.VarChar).Value = txtSurName.Text
    cmd.Parameters.AddWithValue("@CountryId", SqlDbType.Int).Value = Convert.ToInt32(hfContryId.Value)
    cmd.Parameters.AddWithValue("@StateId", SqlDbType.Int).Value = Convert.ToInt32(hfStateId.Value)
    cmd.Parameters.AddWithValue("@CityId", SqlDbType.Int).Value = Convert.ToInt32(hfCityId.Value)
    cmd.ExecuteNonQuery()
    con.Close()
    BindUserDetails()
    ClearControls()
End Sub

Protected Sub Cancel(ByVal sender As Object, ByVal e As EventArgs)
    Me.Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Private Sub ClearControls()
    txtName.Text = ""
    txtSurName.Text = ""
    hfContryId.Value = ""
    hfStateId.Value = ""
    hfCityId.Value = ""
    hfMode.Value = "Save"
    hfId.Value = ""
    btnSubmit.Text = "Save"
End Sub

Private Sub BindUserDetails()
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConStr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("GetUsersDetails")
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Connection = con
            Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
            Dim dt As DataTable = New DataTable()
            da.Fill(dt)
            gvUserDetails.DataSource = dt
            gvUserDetails.DataBind()
        End Using
    End Using
End Sub

<WebMethod()>
Public Shared Function GetCountries() As List(Of ListItem)
    Dim query As String = "SELECT CountryID,CountryName FROM Country"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            Dim cities As List(Of ListItem) = New List(Of ListItem)()
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    cities.Add(New ListItem With {.Value = sdr("CountryID").ToString(), .Text = sdr("CountryName").ToString()})
                End While
            End Using

            con.Close()
            Return cities
        End Using
    End Using
End Function

<WebMethod()>
Public Shared Function GetStates(ByVal countryId As Integer) As List(Of ListItem)
    Dim query As String = "SELECT StateID,StateName FROM State where CountryID = @CountryID"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            Dim states As List(Of ListItem) = New List(Of ListItem)()
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@CountryID", countryId)
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    states.Add(New ListItem With {.Value = sdr("StateID").ToString(), .Text = sdr("StateName").ToString()})
                End While
            End Using

            con.Close()
            Return states
        End Using
    End Using
End Function

<WebMethod()>
Public Shared Function GetCities(ByVal stateId As Integer) As List(Of ListItem)
    Dim query As String = "SELECT  CityID,CityName FROM City where StateID = @StateID"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            Dim cities As List(Of ListItem) = New List(Of ListItem)()
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@StateID", stateId)
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    cities.Add(New ListItem With {.Value = sdr("CityID").ToString(), .Text = sdr("CityName").ToString()})
                End While
            End Using

            con.Close()
            Return cities
        End Using
    End Using
End Function

Screenshot

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html