Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Gridview Has a edit button, on clicking a edit button in gridview a popup appears with edit mode which has cascading drop down in it..but 2nd drop down is not showing its selected value from database..

please help .??

here is my complete code..


<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <link href="Css/bootstrap.min.css" rel="Stylesheet" />
    <link href="Bootstrap/dist/Css/jquery-ui.css" rel="stylesheet" />
    <link href="Css/style.css" rel="stylesheet" />
    <script src="Bootstrap/dist/Js/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="jQuery/jquery-ui.js" type="text/javascript"></script>
    <script src="Bootstrap/dist/Js/jquery.jstepper.js" type="text/javascript"></script>
    <script src="Bootstrap/dist/Js/bootstrap.min.js" type="text/javascript"></script>
    <style>
                
        .hidecolvalue
  {
    display: none;
  }
    </style>
</head>
<body>
      <form id="form1" runat="server">
         
 
 
 
         
       <div class="col-md-1">
            <div class="form-group">
            </div>
        </div>
 
        <div class="col-md-4">
            <div class="form-group">
                <asp:DropDownList ID="ddlState" runat="server" CssClass="form-control" AutoPostBack="false" AppendDataBoundItems="true">
                    <asp:ListItem Text="ALL Group Names" Value="ALL Groups">
                    </asp:ListItem>
                </asp:DropDownList>
            </div>
        </div>
 
 
 
 
        <div class="col-md-1">
            <div class="form-group">
                <asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="Search_Click"  CssClass="btn btn-primary btn-sm" />
            </div>
        </div>
 
        <div class="col-md-1">
            <button type="button" data-target="#AddState"  data-toggle="modal" class="btn btn-primary btn-sm Add State" onclick="AddState();" >Add State</button>
        </div>
 
 
 
  <div id="divGrid">
            <div class="row">
                <div class="col-lg-12">
                    <asp:GridView ID="grdData" runat="server" AutoGenerateColumns="false" CssClass="table table-hover table-bordered" AllowPaging="true"
                        PagerSettings-PageButtonCount="3" GridLines="None" PageSize="10" OnPageIndexChanging="OnPagingChange" OnRowDataBound="grdData_RowDataBound"  >
                        <Columns>
                            <asp:BoundField HeaderText="ID"  DataField="ID" ItemStyle-CssClass="hidecolvalue" HeaderStyle-CssClass="hidecolvalue"  />
                            <asp:BoundField DataField="State" HeaderText="State Name" SortExpression="StateName" />
                            <asp:BoundField DataField="City" HeaderText="City Name" SortExpression="CityName" />
                            <asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
               
                            <asp:TemplateField HeaderText="#Action" ItemStyle-CssClass="display:inline">
                            <ItemTemplate>
                                <asp:Literal ID="ltrlEdit" Text="Edit" runat="server"></asp:Literal>
                            </ItemTemplate>
                            </asp:TemplateField>
                           
                        </Columns>
                        <PagerStyle CssClass="pagination-ys" />
                        <EmptyDataTemplate>No Records Available</EmptyDataTemplate>
                    </asp:GridView>
 
 
                </div>
            </div>
        </div>
 
 
 
   <div class="modal fade" id="AddState" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button class="close" data-dismiss="modal"</button>
                        <h4 class="modal-title">Add State</h4>
                    </div>
                     
                  
                            <div class="modal-body">
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <label for="StateNames">StateNames</label>
                                        </div>
                                        <div class="col-md-9">
                                            <asp:DropDownList ID="ddlStateName" runat="server" CssClass="form-control" AutoPostBack="false" AppendDataBoundItems="true" >
                                                <%--<asp:ListItem Text="ALL State Names" Value="ALL Groups">
                                                </asp:ListItem>--%>
                                            </asp:DropDownList>
                                            <label id="lblStateName" style="display: none; color:red"></label>
                                        </div>
                                    </div>
                                </div>
 
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <label for="CityNames">City Names</label>
                                        </div>
                                        <div class="col-md-5">
                                            <asp:DropDownList ID="ddlCities" runat="server" CssClass="form-control" AutoPostBack="false" AppendDataBoundItems="false">
                                                 
                                            </asp:DropDownList>
                                            <label id ="lbllist" style="display: none; color:red"></label>
 
 
 
                                        </div>
                                    </div>
                                </div>
                            </div>
 
                              
 
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-3">
                                        <label for="inputCode">    Code</label>
                                    </div>
                                    <div class="col-md-4">
                                        <asp:TextBox ID="txtCode" onchange="funchange(this);" runat="server" CssClass="form-control" class="Test"></asp:TextBox>
                                        <label id="lblCode" style="display: none; color: red"></label>
                                         
 
                                       
                                    </div>
                                </div>
                            </div>
 
 
                            <div class="modal-footer">
                                <asp:Button ID="btnSave" runat="server" CssClass="btn btn-primary btn-sm" Text="Save" OnClientClick="return ValidateMe()"/>
                                <button class="btn btn-primary" data-dismiss="modal">Close</button>
                            </div>
                            </div>
                 </div>
                 </div>
                             
 
 function AddState() {
              $('#<%=ddlCities.ClientID%>, #<%=ddlStateName.ClientID%>,#<%=txtCode.ClientID%>').val('');
              
           
          }
 
 
 function ValidateMe() {
            if (isNullOrEmpty($('#<%=ddlStateName.ClientID%>').val())) {
                $('#lblStateName').text('Please Select Doctor Name').show().fadeOut(3000);
                return false;
 
            }
            if (isNullOrEmpty($('#<%=ddlCities.ClientID%>').val())) {
            $('#lbllist').text('Please enter Upper Limit').show().fadeOut(3000);
            return false;
        }
        if (isNullOrEmpty($('#<%=txtCode.ClientID%>').val())) {
            $('#lbllblCode').text('Please enter Code').show().fadeOut(3000);
            return false;
        }
         
            alert(' Details Successfully added..');
 
            $('#AddState').modal('hide')
            return true;
 
          
        };
 
 
 
  $(function () {
 
              $('#<%=ddlCities.ClientID %>').attr('disabled', 'disabled');
 
               $('#<%=ddlCities.ClientID %>').append('<option selected="selected" value="0">Select City</option>');
 
               $('#<%=ddlStateName.ClientID %>').change(function () {
                   
                   var Cities = $('#<%=ddlStateName.ClientID%>').val()
                   $('#<%=ddlCities.ClientID %>').removeAttr("disabled");
 
                   $.ajax({
                       type: "POST",
                       url: "Citycheck.aspx/BindCities",
                       data: "{'Cities':'" + Cities + "'}",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       success: function (msg) {
                           var j = jQuery.parseJSON(msg.d);
                           var options;
                           for (var i = 0; i < j.length; i++) {
                               options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                           }
                           $('#<%=ddlCities.ClientID %>').html(options)
                       },
                       error: function (data) {
                           alert('Something Went Wrong')
                       }
                   });
               });
 
           });
 
 
function Edit(RecordID) {
 $.ajax({
 url: 'citycheck.aspx/GetCityByStateCode?ts=' + $.now(),
 contentType: 'application/json',
 type: 'POST',
 data: JSON.stringify({ id: RecordID }),
 success: function (res) {
 var obj = JSON.parse(res.d);
 $('#<%=hdnRecordId.ClientID%>').val(RecordID);
 $('#<%=ddlStateName.ClientID%>').val(obj.ID).change();
  
 $('#<%=ddlCities.ClientID%>').val(obj.CityID).change();
 $('#<%=txtCode.ClientID%>').val(obj.code);
  
 
 },
 error: function (err) {
 }
 });
 
 }


What I have tried:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.IO;
 
namespace cascade
{
    public partial class Citycheck : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbConn12"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlState.DataSource = GetStateNames();
                ddlState.DataTextField = "StateName";
                ddlState.DataValueField = "StateCode";
                ddlState.DataBind();
 
 
                ddlStateName.DataSource = GetStateNames();
                ddlStateName.DataTextField = "StateName";
                ddlStateName.DataValueField = "StateCode";
                ddlStateName.DataBind();
 
                ddlStateName.Items.Insert(0, new ListItem("All State Names", ""));
                BindGrid();
            }
 
        }
 
        protected DataSet GetStateNames()
        {
            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand("sp_StateNames", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                con.Open();
                da.Fill(ds);
                con.Close();
            }
 
            catch (Exception ex)
            {
                Response.Write(ex.Message);
 
            }
            return ds;
 
        }
 
        protected void BindGrid()
        {
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand("Sp_CityData", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
 
          
                    cmd.Parameters.AddWithValue("@StateCode", ddlState.SelectedItem.Value);
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
 
                    if (dt.Rows.Count > 0)
                    {
                        grdData.DataSource = dt;
                        grdData.DataBind();
                    }
                    else
                    {
                        grdData.DataSource = dt;
                        grdData.DataBind();
                    }
                }
            }
        }
 
        protected void Search_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
 
        protected void OnPagingChange(object sender, GridViewPageEventArgs e)
        {
 
            grdData.PageIndex = e.NewPageIndex;
            this.BindGrid();
 
        }
[WebMethod]
        public static string BindCities(string Cities)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbConn12"].ToString();
            StringWriter builder = new StringWriter();
            String strQuery = "select CityCode1 , CityName from CityDetails where StateCode = @stateCode  ";
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strQuery;
                    cmd.Parameters.AddWithValue("@stateCode", Cities);
                    cmd.Connection = con;
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    con.Close();
                }
            }
            DataTable dt = ds.Tables[0];
            builder.WriteLine("[");
            if (dt.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select City\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["CityName"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["CityCode1"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select City\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }
 
 
        [WebMethod]
        public static string GetCityByStateCode(int id)
        {
            Citydata citydata = null;
            string cs = ConfigurationManager.ConnectionStrings["dbConn12"].ToString();
 
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand("GetCityByStateCode", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@RecordID", id);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable table = new DataTable();
                    da.Fill(table);
                    foreach (DataRow row in table.Rows)
                    {
                        citydata = new CityData()
                        {
                            RecordID = row["RecordID"].ToString(),
                            StateName = row["StateName"].ToString(),
                            CityName = row["CityName"].ToString(),
                            ID = row["StateCode"].ToString(),
                            CityID = row["CityCode1"].ToString(),
                            code = Convert.ToInt32(row["Code"].ToString()),
                             
                        };
                    }
                }
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(citydata);
        }
 
        protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
 
                Literal ltrlEdit = e.Row.FindControl("ltrlEdit") as Literal;
 
                ltrlEdit.Text = string.Format("<button id='edit_{0}' onclick='Edit({0})' type='button'text='Edit'  data-toggle='modal' class='btn btn-primary btn-sm pull-left' data-target='#AddState' title='Add State'>Edit</button>",
                    DataBinder.Eval(e.Row.DataItem, "RecordID"),
                   DataBinder.Eval(e.Row.DataItem, "RecordID").ToString());
 
 
 
            }
 
 
 
        }
 
 
 
    }
}
Posted
Updated 16-Jul-17 18:15pm

1 solution

try
$.ajax({
                     type: "POST",
                     async:false,
                     url: "Citycheck.aspx/BindCities",


$('#ddlCities').val('cityid');
 
Share this answer
 
v2
Comments
Mahesh2223 17-Jul-17 0:55am    
No bro still selected value is not displayed in drop down
Mahesh2223 17-Jul-17 1:10am    
i am getting all values but 2nd drop down value is not coming.
Karthik_Mahalingam 17-Jul-17 1:36am    
run this in console and check
$('#ddlCities').val('cityid');
Mahesh2223 28-Jul-17 7:31am    
bro help.??
https://www.codeproject.com/Questions/1198781/Autocomplete-dropdown-based-on-radio-button-checke
Karthik_Mahalingam 28-Jul-17 11:30am    
what do u mean by autocomplete,
by typing the first char it should populate the items starts with the char ?

coz the question and the code makes no sense

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900