Thursday, 16 March 2017

Bind Data in DropDown Dynamically using Web Methods in Asp.Net

Database


1> Create a Table in SQL with the name country.
2> Insert atleast 5 country name within the table.
3>Create a stored procedure with the name

Create proc country_bind_sp
as
begin
select id,country from country
end


Web.Config File

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="constr" value="Data source=*****;Initial catalog=*****; user id=*****; password=*****;"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>




Business Layer

Create a class with the name BusinessLayer to write the ADO Code.


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace DropDownBind
{
    public class BusinessLayer
    {
        string constring = ConfigurationManager.AppSettings["constr"].ToString();
        public DataTable countrybind()
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("country_bind_sp", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                adapt.Fill(dt);
                return dt;
            }
        }
    }
}


Web Form

ADD Web Form in Project with the name Country

Country.Aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Country.aspx.cs" Inherits="DropDownBind.Country" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            binding();
        });

        function binding()
        {
            debugger
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Country.aspx/BindCountry",
                data: "{}",
                dataType: "json",
                success: function (data) {
                    debugger;
                        $("#<%=ddl_country.ClientID %>").append($("<option></option>").val(0).html("-Select SubCategory-"));
                    $.each(data.d, function (key, value) {
                        $("#<%=ddl_country.ClientID %>").append($("<option></option>").val(value.DataValueField).html(value.DataTextField));
                    });
                },
                error: function (result) { }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddl_country" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>


Country.Aspx.cs


  [WebMethod]
        public static Country1[] BindCountry()
        {
            List<Country1> cntry = new List<Country1>();
            BusinessLayer objbusiness = new BusinessLayer();
            DataTable dt = objbusiness.countrybind();
           for(int i=0;i<dt.Rows.Count;i++)
            {
                Country1 cont = new Country1();
                cont.DataValueField = Convert.ToInt32(dt.Rows[i]["id"]);
               cont.DataTextField = dt.Rows[i]["country"].ToString();
                cntry.Add(cont);
            }
            return cntry.ToArray();
        }

       
    }
    public class Country1
    {
        public int DataValueField { get; set; }
        public string DataTextField { get; set; }
    }
}

If you have any query please post in the comment
                                                                       sharmarahulsoftwareengineer.blogspot.in

No comments:

Post a Comment

Insert, Delete, Update Using Entity Framework and LINQ in ASP.NET 1> Create Database First 2> Create Table 3> Add ADO...