Wednesday, 29 February 2012

jquery popup

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
     <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
    <style type="text/css">
    #popupBoxClose
 {
    font-size:10px; 
    line-height:15px; 
    right:5px; 
    top:5px; 
    position:absolute; 
    color:#6fa5e2; 
    font-weight:500;     
}
#popup_box {
    display:none; /* Hide the DIV */
    position:fixed; 
    _position:absolute; /* hack for internet explorer 6 */ 
    height:300px; 
    width:600px; 
    background:#FFFFFF; 
    left: 300px;
    top: 150px;
    z-index:100; /* Layering ( on-top of others), if you have lots of layers: I just maximized, you can change it yourself */
    margin-left: 15px; 
   
    /* additional features, can be omitted */
    border:2px solid #999999;     
    padding:15px; 
    font-size:15px; 
    -moz-box-shadow: 0 0 5px #ff0000;
    -webkit-box-shadow: 0 0 5px #ff0000;
  
}

    </style>
     <script type="text/javascript">
         $(document).ready(function () {
             Sys.WebForms.PageRequestManager.getInstance().add_endRequest(JqueryAction);
             JqueryAction();
         });
         function ShowPopUp()
         {
             //e.preventDefault();
             $('#popup_box').slideDown("slow");
         }
         function JqueryAction()
          {
             //            $("#AddCategory").click(function (e) {
             //                e.preventDefault();
             //                $('#popup_box').fadeIn();
             //            });
             $('#popupBoxClose').click(function () {
                 $('#popup_box').slideUp("slow");
             });
         }
         $(document).ready
         (
         function () {
             $("#ab").click(
          function () {
              ShowPopUp();
          }
         )
         }
         )
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
  <a href="#" id="ab" >Press Me</a>
<div id="popup_box">
            <a id="popupBoxClose">Close</a><br />
      hihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 
       hihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
       hihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
       hihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
</div>

    </form>
</body>
</html>

Use of ajax HtmlEditorExtender

Design a table in ur database:
Design the user inter face like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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>
    <style type="text/css">
.accordionContent
{
background-color: #D3DEEF;
border-color: -moz-use-text-color #2F4F4F #2F4F4F;
border-right: 1px dashed #2F4F4F;
border-style: none dashed dashed;
border-width: medium 1px 1px;
padding: 10px 5px 5px;
width:20%;
}
.accordionHeaderSelected
 {
background-color: #5078B3;
border: 1px solid #2F4F4F;
color: white;
cursor: pointer;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
margin-top: 5px;
padding: 5px;
width:20%;
}
.accordionHeader
{
background-color: #2E4D7B;
border: 1px solid #2F4F4F;
color: white;
cursor: pointer;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
margin-top: 5px;
padding: 5px;
width:20%;
}
.href
{
color:White;
font-weight:bold;
text-decoration:none;
}
</style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
    <asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
    <table align="center">
    <tr><td>  <asp:HtmlEditorExtender ID="HtmlEditorExtender1" runat="server" TargetControlID="tb">
        </asp:HtmlEditorExtender>
        <asp:TextBox ID="tb" runat="server" TextMode="MultiLine" Height="300" Width="600"></asp:TextBox></td></tr>
        <tr><td align="center"><asp:Button ID="btn" runat="server" Text="Save" Width="80"
                onclick="btn_Click" />&nbsp;<asp:Button ID="Button1" runat="server" Text="Reset" Width="80" /></td></tr>
        <tr><td>
        <asp:Repeater ID="rpt" runat="server">
        <ItemTemplate>
        <asp:Literal ID="ltr" runat="server" Text='<%#Eval("name")%>'></asp:Literal>
        </ItemTemplate>
        <SeparatorTemplate>
        <hr />
        </SeparatorTemplate>
        </asp:Repeater>
        </td></tr>
    </table>
    </ContentTemplate>
    </asp:UpdatePanel>
     
    </div>
    </form>
</body>
</html>


 C# CODE :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
#region
    DataClassesDataContext o =new DataClassesDataContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
#endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            view();
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        EMP p = new EMP();
        p.NAME = tb.Text;
        o.EMPs.InsertOnSubmit(p);
        o.SubmitChanges();
        view();
    }
    void view()
    {
        var m = from x in o.EMPs select x;
        rpt.DataSource = m;
        rpt.DataBind();
    }
}


4-Tier Architecture in ASP.NET with C#

Download


 Download source code for 4-Tier Architecture in ASP.NET with C#
Well, the architecture I am going to demonstrate here is just enhancement of 3-Tier archicture. In this architecture; you no need of writing long function parameters throughout the layers (as in traditionally 3-Tier archicture has to) and the actual objects of the application will be in a separate tier so that in future you can separately use these objects for enhancements. Change in the object definition can be done without touching the entire Business Access Layers ............

Let me explain you step-wise process of creatioin of 4-Tier architecture application.

In this application, I am going to take example of a Person that will have 3 properties: FirstName, LastName, Age. We will create a separate pages to insert these records (default.aspx) into database and list,update,delete records (list.aspx) from database.
design a table in ur database  the table name is EMP
create a procedure on ur database the procedure like this


CREATE PROCEDURE EMP1
(
@EID INT=NULL,
@NAME VARCHAR(50)=NULL,
@MARK INT
)
AS
BEGIN
SET NOCOUNT ON
IF @MARK=1
INSERT INTO EMP VALUES(@EID,@NAME)
ELSE IF @MARK=2
UPDATE EMP SET NAME=@NAME WHERE EID=@EID
ELSE IF @MARK=3
DELETE FROM EMP WHERE EID=@EID
ELSE IF @MARK=4
SELECT * FROM EMP
SET NOCOUNT OFF
END


In this application we will have following 4-Tiers
1. Business Object [BO]
2. Business Access Layer [BAL]
3. Data Access Layer [DAL]
4. User Interface. [UI]

Add a class on ur project, the class name is BO.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class BO
{
    private int eid;
    private string name;
    public int EID
    {
        get
        {
            return eid;
        }
        set
        {
            eid = value;
        }
    }
    public string NAME
    {
        set
        {
            name = value;
        }
        get
        {
            return name;
        }
    }
}
Add another class on ur project, the class name is DAL.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public class DAL
{
    SqlCommand cm;
    SqlConnection cn;
    SqlDataAdapter da;
    DataTable dt = new DataTable();
  
    public DAL()
    {
        cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
        cn.Open();
    }
    public int insert(BO o)
    {
        try
        {

            cm = new SqlCommand("emp1", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@eid", o.EID);
            cm.Parameters.AddWithValue("@name", o.NAME);
            cm.Parameters.AddWithValue("@mark", 1);
            return cm.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }
        finally
        {
            cm.Dispose();
            cn.Close();
            cn.Dispose();
        }
    }
    public int update(BO o)
    {
        try
        {

            cm = new SqlCommand("emp1", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@eid", o.EID);
            cm.Parameters.AddWithValue("@name", o.NAME);
            cm.Parameters.AddWithValue("@mark", 2);
            return cm.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }
        finally
        {
            cm.Dispose();
            cn.Close();
            cn.Dispose();
        }
    }
    public int delete(BO o)
    {
        try
        {

            cm = new SqlCommand("emp1", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@eid", o.EID);
            cm.Parameters.AddWithValue("@mark", 3);
            return cm.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }
        finally
        {
            cm.Dispose();
            cn.Close();
            cn.Dispose();
        }
    }
    public DataTable view()
    {
        try
        {

            cm = new SqlCommand("emp1", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@mark", 4);
            da = new SqlDataAdapter(cm);
            da.Fill(dt);
            return dt;
        }
        catch
        {
            throw;
        }
        finally
        {
            cm.Dispose();
            cn.Close();
            cn.Dispose();
            da.Dispose();
        }
    }
}

Add another class on ur project, the class name is BAL.CS

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


public class BAL
{
    public int insert(BO o)
    {
        DAL p = new DAL();
        try
        {
            return p.insert(o);
        }
        catch
        {
            throw;
        }
        finally
        {
            p = null;
        }
    }
    public int update(BO o)
    {
        DAL p = new DAL();
        try
        {
            return p.update(o);
        }
        catch
        {
            throw;
        }
        finally
        {
            p = null;
        }
    }
    public int delete(BO o)
    {
        DAL p = new DAL();
        try
        {
            return p.delete(o);
        }
        catch
        {
            throw;
        }
        finally
        {
            p = null;
        }
    }
    public  DataTable  view()
    {
        DAL p = new DAL();
        try
        {
            return p.view();
        }
        catch
        {
            throw;
        }
        finally
        {
            p = null;
        }
    }
}

design the the inter face like this :
 design code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <style type="text/css">
    .A
    {
        width:940px;
    }
    .B
    {
        width:360px;
        text-align:right;
        float:left;
        padding-top:3px;
        list-style:none;
    }
    .C
    {
          width:20px;
        text-align:center;
        float:left;
        padding-top:3px;
        list-style:none;
        font-weight:bolder;
    }
     .D
    {
          width:560px;
        text-align:left;
        float:left;
        padding-top:3px;
        list-style:none;
      
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
     <center>
    <div class="A">
    <asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
    <li class="A" style="list-style:none; text-align:center">&nbsp;<asp:Label ID="lb" runat="server"></asp:Label></li>
     <li class="B">EID</li>
      <li class="C">:</li>
      <li class="D"><asp:TextBox ID="tb" runat="server"></asp:TextBox></li>
      <li class="B">NAME</li>
      <li class="C">:</li>
      <li class="D"><asp:TextBox ID="tb1" runat="server" Width="200"></asp:TextBox></li>
      <li class="B">&nbsp;</li>
      <li class="C">&nbsp;</li>
      <li class="D"><asp:Button ID="btn" runat="server" Text="Save" Width="80"
              onclick="btn_Click" />&nbsp;<asp:Button ID="Button1" runat="server" Text="Reset" Width="80" /></li>
      <li class="B">&nbsp;</li>
      <li class="C">&nbsp;</li>
      <li class="D"><asp:GridView ID="gv" DataKeyNames="eid" runat="server" AllowPaging="True"
              onpageindexchanging="gv_PageIndexChanging" onrowdeleting="gv_RowDeleting"
              PageSize="2" onrowcancelingedit="gv_RowCancelingEdit"
              onrowediting="gv_RowEditing" onrowupdating="gv_RowUpdating">
          <Columns>
              <asp:CommandField HeaderText="UPDATE" ShowEditButton="True" ShowHeader="True" />
              <asp:CommandField HeaderText="DELETE" ShowDeleteButton="True"
                  ShowHeader="True" />
          </Columns>
          </asp:GridView></li>
  
    </ContentTemplate>
    </asp:UpdatePanel>
    </div>
     </center>
    </form>
</body>
</html>
C# CODE:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    BO o = new BO();
    BAL p = new BAL();
    int i;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            view();
    }
    void view()
    {
        gv.DataSource = p.view();
        gv.DataBind();
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        o.EID = Convert.ToInt32(tb.Text);
        o.NAME = tb1.Text;
        i = p.insert(o);
        if (i != 0)
        {
            lb.Text = "One record saved.";
            lb.ForeColor = Color.Green;
            view();
        }
        else
        {
            lb.Text = "Error on save.";
            lb.ForeColor = Color.Red;
        }
    }
    protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;
        view();
    }
    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        o.EID = Convert.ToInt32(gv.DataKeys[e.RowIndex].Value);
        i = p.delete(o);
        if (i != 0)
        {
            lb.Text = "One record deleted.";
            lb.ForeColor = Color.Green;
            view();
        }
        else
        {
            lb.Text = "Error on delete.";
            lb.ForeColor = Color.Red;
        }
    }
    protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gv.EditIndex = -1;
        view();
    }
    protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gv.EditIndex = e.NewEditIndex;
        view();
    }
    protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        o.EID = Convert.ToInt32(gv.DataKeys[e.RowIndex].Value);
        o.NAME = ((TextBox)gv.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
        i = p.insert(o);
        if (i != 0)
        {
            lb.Text = "One record updated.";
            lb.ForeColor = Color.Green;
            gv.EditIndex = -1;
            view();
        }
        else
        {
            lb.Text = "Error on update.";
            lb.ForeColor = Color.Red;
        }
    }
}


Monday, 27 February 2012

Ajax Cascading Dropdownlist using webservice,linq in asp.net

DESIGN THE CODE LIKE THIS:
<form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
    <asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
    <table align="center">
    <tr><td>COUNTRY</td><td><asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>&nbsp;<asp:CascadingDropDown ID="CascadingDropDown1" Category="COUNTRY" runat="server" TargetControlID="ddl" ServiceMethod="x" ServicePath="~/WebService2.asmx" PromptText="Select">
        </asp:CascadingDropDown>
    </td></tr>
    <tr><td>STATE</td><td><asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList>&nbsp;<asp:CascadingDropDown ID="cs" runat="server" Category="STATE" TargetControlID="ddl1" ParentControlID="ddl" PromptText="Select" ServicePath="~/WebService2.asmx" ServiceMethod="yy"></asp:CascadingDropDown></td></tr>
    </table>
    </ContentTemplate>
    </asp:UpdatePanel>
    </div>
    </form>

WEBSERVICE CODE :

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using AjaxControlToolkit;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class WebService2 : System.Web.Services.WebService
{
    DataClassesDataContext o = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
    int i;
    string b, c;
    List<CascadingDropDownNameValue> p = new List<CascadingDropDownNameValue>();
    [WebMethod]
    public CascadingDropDownNameValue[] x()
    {
        var m = from a in o.COUNTRies select a;
        foreach (var n in m)
        {
            b =Convert.ToString( n.CID);
            c = n.CNAME;
            p.Add(new CascadingDropDownNameValue(c, b));
        }
        return p.ToArray();
    }
    [WebMethod]
    public CascadingDropDownNameValue[] yy(string knownCategoryValues)
    {
        StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        i = Convert.ToInt32(sd["COUNTRY"]);
        var n = from d in o.STATEs where d.CID == i select d;
        foreach (var m in n)
        {
            b = Convert.ToString(m.SID);
            c = m.SNAME;
            p.Add(new CascadingDropDownNameValue(c, b));
        }
        return p.ToArray();
    }
  
  
   
}

Ajax AutoCompleteExtender using webservice,linq

DESIGN THE PAGE LIKE THIS :
<form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
    <center>
    <asp:TextBox ID="tb" runat="server"></asp:TextBox><asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="tb" CompletionSetCount="12" CompletionInterval="1" MinimumPrefixLength="2" ServicePath="~/WebService.asmx" ServiceMethod="x"
        runat="server">
    </asp:AutoCompleteExtender>
    </center>
    </div>
    </form>
WEBSERVICE CODE :

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    DataClassesDataContext o = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
    int i;
    [WebMethod]
   public string[] x(string prefixText)
    {
        i = 0;
        var m = from y in o.EMPs where y.NAME.StartsWith(prefixText) select y;
        string[] s = new string[m.Count()];
        foreach (var n in m)
        {
            s[i] = n.NAME;
            i++;
        }
        return s;
     
    }
}

what is partial class in asp.net

Definition : A class defined in  two or more files is called a partial class. The keyword partial is used to define the class. When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. During compile time all the partial class are compiled into one type only.

public partial class PartialClass
{
    public void MethodA()
    {
        Console.WriteLine("I am A!");
    }
}

public partial class PartialClass
{
    public void MethodB()
    {
        Console.WriteLine("I am B!");
    }
}


If we try to call methods of this class we can see something like this on screen.
Methods of partial class

Saturday, 25 February 2012

Ajax Cascading DropDownList With Database Example in GridView

Note-Add this in page tag on the design page validateRequest="false"  enableEventValidation="false"
In this example i've implemented Ajax cascading drop down list in EditItemTemaplete of GridView for updation of records in grid by fetching data from database to populate dropdowns,I've also implemented ajax auto complete extender textbox in it to edit name field

Make sure you have created ajax enabled website and installed ajax toolkit and ajax web extensions properly

In this example gridview displays Name, City, and Country on page load,

And City and Country field turns into cascading dropdown list when user clicks on Edit link

Ajax cascading dropdown extender uses webservice to fetch data from database and populate dropdowns, city dropdown is populated based on country selected in country dropdown

Important points to remember

1. Put AjaxControlToolkit.dll in bin folder of your application.
2. Set EventValidation to false in page directive of your aspx page

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

Here is explanation why you need to turn it off ?
in order for the values to be submitted, EventValidation needs to be disabled for the page. EventValidation ensures that the values in each control match the values that were present when the page was rendered, but since these drop downs are populating on the client side, this is never true.

3. If you are getting Error method 500 or 12031 than read this to resolve this error

4. Webservice must have the webmethod with following signature and exact parameters
[WebMethod]
public CascadingDropDownNameValue[] GetColorsForModel(
string knownCategoryValues,
string category)

You can change the method name but return type must be CascadingDropDownNameValue[] with knownCategoryValues,category as parameters

First of all add a new webservice and name it CascadingDropDown.asmx
In code behind of this asmx file write following code
Add these namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Collections.Specialized;

/// <summary>
/// Summary description for CascadingDropDown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Create global Connection string
string strConnection = ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString;

public CascadingDropDown () {

//Uncomment the following line if using designed components 
//InitializeComponent(); 
}
/// <summary>
/// WebMethod to populate country Dropdown
/// </summary>
/// <param name="knownCategoryValues"></param>
/// <param name="category"></param>
/// <returns>countrynames</returns>
[WebMethod]
public CascadingDropDownNameValue[] GetCountries
(string knownCategoryValues, string category)
{
//Create sql connection and sql command
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * from Country";

//Create dataadapter and fill the dataset
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();

//create list and add items in it 
//by looping through dataset table
List<CascadingDropDownNameValue> countryNames
= new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string countryID = dRow["CountryID"].ToString();
string countryName = dRow["CountryName"].ToString();
countryNames.Add(new CascadingDropDownNameValue
(countryName, countryID));
}
return countryNames.ToArray();


}

[WebMethod]
public CascadingDropDownNameValue[] GetCities
(string knownCategoryValues, string category)
{
int countryID;
//this stringdictionary contains has table with key value
//pair of cooountry and countryID
StringDictionary countryValues =
AjaxControlToolkit.CascadingDropDown.
ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countryValues["Country"]);

SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@CountryID", countryID);
cmd.CommandText =
"Select * from City where CountryID = @CountryID";

SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();
List<CascadingDropDownNameValue> cityNames =
new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string cityID = dRow["CityID"].ToString();
string cityName = dRow["CityName"].ToString();
cityNames.Add(new CascadingDropDownNameValue
(cityName, cityID));
}
return cityNames.ToArray();
}

}


Now in html source of aspx page I've put two dropdowns in EditItemTemaplate of gridview
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>


Here TargetControlID is id of dropdown on which cascading dropdown is to be implemented ,Service path is path to webservice and ServiceMethod is method to fetch the data from databse and populate dropdown

You also need to add reference to webservive in script manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>


The complete html source is like this
<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowUpdating="GridView1_RowUpdating">

<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Bind("ID") %>'>
</asp:Label>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name"
SortExpression="Name">
<ItemTemplate>
<asp:Label ID = "lblName" runat="server"
Text='<%#Eval("Name") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%#Bind("Name") %>' >
</asp:TextBox>
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtName"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12" />
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Country"
SortExpression="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%#Eval("Country") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City"
SortExpression="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"
OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown2"
runat="server"
Category="City"
TargetControlID="ddlCity"
ParentControlID="ddlCountry"
PromptText="-Select City-"
LoadingText="Loading Cities.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCities">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="SELECT [ID], [Name], [City],[Country]
FROM [Location]"
UpdateCommand="Update Location set [Name] = @Name,
[City] = @City,[Country] = @Country
where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
<asp:Parameter Name="Country"/>
<asp:Parameter Name="City"/>
</UpdateParameters>
</asp:SqlDataSource>

</div>
</form> 
</body>
</html>


Finally write this code in code behind of aspx page to update record
protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
//Find dropdown to get selected Item text  
DropDownList ddlGridCountry = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCountry");
string strCountry =
ddlGridCountry.SelectedItem.Text.ToString();

DropDownList ddlGridCity = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCity");
string strCity =
ddlGridCity.SelectedItem.Text.ToString();

SqlDataSource1.UpdateParameters.Clear();
SqlDataSource1.UpdateParameters.Add
("Country", strCountry);
SqlDataSource1.UpdateParameters.Add("City", strCity);
}


Hope this helps

I wrote similar article in case you don't use ajax , than u can go through this

1. C#.NET Articles -Cascading DropDownList Populate dropdown based on selection of other dropdown in ASP.NET

2. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Download the sample code attached

Dynamically Create Multiple Web User Control In a Page With Click Event Functionality

I have created a simple application having 3 user controls as

  • WebUserControl1.ascx
  • WebUserControl2.ascx
  • WebUserControl3.ascx
Also i have a web Page as
  • DynamicUserControl.aspx
First i have  created a  web user control dynamicaaly into the web page but first usercontrol event firing well but for second onwards it needed double click. Finally i got the solution if some one has better then please tell me.

Here is my First WebUsercontrol1.ascx Code:-

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl1.ascx.cs" Inherits="UserControl_WebUserControl1" %>
<%@ Reference Control="~/UserControl/WebUserControl2.ascx" %>

<asp:Button ID="Next1" runat="server" Text="Next" onclick="Next1_Click" />

WebUsercontrol1.ascx.cs Code:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


    public partial class UserControl_WebUserControl1 : System.Web.UI.UserControl
    {
        public event EventHandler Next1Click;

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void Next1_Click(object sender, EventArgs e)
        { 
            Session["test"] = "2";
            Next1Click(sender, e);
            UserControl_WebUserControl2 ucSimpleControl = (UserControl_WebUserControl2)LoadControl("~/UserControl/WebUserControl2.ascx");

            PlaceHolder phContactDetails = (PlaceHolder)Page.FindControl("ControlHolder");
            phContactDetails.Controls.Clear();
            phContactDetails.Controls.Add(ucSimpleControl);
            ucSimpleControl.Next2Click += new EventHandler(ucSimpleControl_Next2Click);
          
        }

        protected void ucSimpleControl_Next2Click(object sender, EventArgs e)
        {
            Response.Write("It's working");
        }
    }
Here is my second WebUsercontrol2.ascx Code:-

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl2.ascx.cs" Inherits="UserControl_WebUserControl2" %>
<%@ Reference Control="~/UserControl/WebUserControl3.ascx" %>
<asp:Button ID="Next2" runat="server" Text="Next2" onclick="Next2_Click" />



WebUsercontrol2.ascx.cs Code:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
  public partial class UserControl_WebUserControl2 : System.Web.UI.UserControl
    {
        public event EventHandler Next2Click;
       
        protected void Page_Load(object sender, EventArgs e)
        {
           

        }
        protected void Next2_Click(object sender, EventArgs e)
        { 
            Session["test"] = "3";
            Next2Click(sender, e);
            UserControl_WebUserControl3 ucSimpleControl = (UserControl_WebUserControl3)LoadControl("~/UserControl/WebUserControl3.ascx");

            PlaceHolder phContactDetails = (PlaceHolder)Page.FindControl("ControlHolder");
            phContactDetails.Controls.Clear();
            phContactDetails.Controls.Add(ucSimpleControl);
            ucSimpleControl.Next3Click += new EventHandler(ucSimpleControl_Next3Click);
           
        }
        protected void ucSimpleControl_Next3Click(object sender, EventArgs e)
        {
            Response.Write("It's working");
        }
        
    }

Here is my Third WebUsercontrol3.ascx Code:-

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl3.ascx.cs" Inherits="UserControl_WebUserControl3" %>
<asp:Button ID="Next3" runat="server" Text="Next3" onclick="Next3_Click" />


WebUsercontrol3.ascx.cs Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;




    public partial class UserControl_WebUserControl3 : System.Web.UI.UserControl
    {
        public event EventHandler Next3Click;
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void Next3_Click(object sender, EventArgs e)
        {
            Next3Click(sender, e);
          
        }
        
    }


Finally This is my DynamicUserControl.aspx:-

Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicUserControl.aspx.cs" Inherits="DynamicUserControl" %>
<%@ Reference Control="~/UserControl/WebUserControl1.ascx" %>
<%@ Reference Control="~/UserControl/WebUserControl2.ascx" %>
<%@ Reference Control="~/UserControl/WebUserControl3.ascx" %>
<%@ Register Src="~/UserControl/WebUserControl1.ascx" TagName="FirstControl" TagPrefix="gis" %>


<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="ControlHolder" runat="server"></asp:PlaceHolder>
        <br />
        
    </div>
    <asp:HiddenField ID="hf" runat="server" />
   
    </form>
</body>
</html>

My Code Behind:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DynamicUserControl : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["test"] = null;
        }
        int id = 1;
        int i=0;
        if (Session["test"] != null)
        {
           
            id = int.Parse(Session["test"].ToString());
        
        }
        if (Session["test"] == null)
        {
            UserControl_WebUserControl1 ucSimpleControl = (UserControl_WebUserControl1)LoadControl("~/UserControl/WebUserControl" + id + ".ascx");
            ControlHolder.Controls.Clear();
            ControlHolder.Controls.Add(ucSimpleControl);

            ucSimpleControl.Next1Click += new EventHandler(ucSimpleControl_Next1Click);
        }
        if (id == 2)
        {
            UserControl_WebUserControl2 ucSimpleControl = null;
           
                ucSimpleControl = (UserControl_WebUserControl2)LoadControl("~/UserControl/WebUserControl" + id + ".ascx");

            
                ControlHolder.Controls.Clear();
                for (i = 1; i <= id; i++)
                {
            ControlHolder.Controls.Add(ucSimpleControl);
                }
            ucSimpleControl.Next2Click += new EventHandler(ucSimpleControl_Next2Click);
        }
        

        if (id == 3)
        {
            UserControl_WebUserControl3 ucSimpleControl=null;
           
             ucSimpleControl = (UserControl_WebUserControl3)LoadControl("~/UserControl/WebUserControl" + id + ".ascx");

            
            ControlHolder.Controls.Clear();
            for (i = 1; i <= id; i++)
            {
            ControlHolder.Controls.Add(ucSimpleControl);
            } 
                ucSimpleControl.Next3Click += new EventHandler(ucSimpleControl_Next3Click);
          
        }

       
            
            
        

    }
    
    protected void ucSimpleControl_Next1Click(object sender, EventArgs e)
    {
        
        Response.Write("The First usercontrol working fine");
    }

    protected void ucSimpleControl_Next2Click(object sender, EventArgs e)
    {
        Response.Write("The Second usercontrol working fine");
    }
    protected void ucSimpleControl_Next3Click(object sender, EventArgs e)
    {
        Response.Write("The Third usercontrol working fine");
    }
   
}

The Screen Shot of my Folder and user control is :