Sep 09
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataRelation.aspx.cs"
Inherits="DataRelation" %>

<%@ Import Namespace="System.Data" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:GridView ID="GridView2"
DataSource='<%#((DataRowView)Container.DataItem).CreateChildView("ParentChild") %>'
                            runat="server" AutoGenerateColumns="False">
                            <Columns>
                                <asp:BoundField DataField="Dept"
HeaderText="Department" />
                                <asp:BoundField DataField="name"
HeaderText="Name" />
                            </Columns>
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
</form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataRelation : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {

          GridView1.DataSource = CreateDS().Tables["Company"];
          GridView1.DataBind();

      }

  }
  private DataSet CreateDS()
  {
      DataSet ds;
      if (Session["DataList_ParentChild"] == null)
      {
          ds = new DataSet();
          DataTable dt = new DataTable("Company");
          DataRow dr;
          dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
          dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
          dt.Columns.Add(new DataColumn("Address", typeof(string)));
          dt.Columns.Add(new DataColumn("Name", typeof(string)));
          dt.Columns.Add(new DataColumn("Dept", typeof(string)));
          for (int i = 1; i < 10; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = "Company " + i;
              dr[2] = "Address " + i;
              dr[3] = "Manager name";
              dr[4] = "Adminstration";
              dt.Rows.Add(dr);
          }
          ds.Tables.Add(dt);
          DataColumn[] Parent_PKColumns = new DataColumn[1];
          Parent_PKColumns[0] = dt.Columns["ID"];
          dt.PrimaryKey = Parent_PKColumns;

          dt = new DataTable("Employees");
          dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
          dt.Columns.Add(new DataColumn("CompanyID", typeof(Int32)));
          dt.Columns.Add(new DataColumn("Name", typeof(string)));
          dt.Columns.Add(new DataColumn("Dept", typeof(string)));
          for (int i = 1; i < 10; i++)
          {
              int imax = 0;
              if (i % 2 == 0) imax = 5;
              else imax = 4;
              for (int y = 2; y < imax; y++)    //3 emplyees for each company
              {
                  dr = dt.NewRow();
                  dr[0] = y + i * 5;
                  dr[1] = i;
                  dr[2] = "Employee # " + dr[0];
                  dr[3] = "Dept # " + (y + i);
                  dt.Rows.Add(dr);
              }
          }
          DataColumn[] Child_PKColumns = new DataColumn[1];
          Child_PKColumns[0] = dt.Columns["ID"];
          dt.PrimaryKey = Child_PKColumns;
          ds.Tables.Add(dt);
          DataColumn[] Child_FKColumns = new DataColumn[1];
          Child_FKColumns[0] = dt.Columns["CompanyID"];

          ds.Relations.Add("ParentChild", Parent_PKColumns, Child_FKColumns);
          Session["DataList_ParentChild"] = ds;
      }
      else
      {
          ds = (DataSet)Session["DataList_ParentChild"];
      }
      return ds;

  }
}
Sep 09
  Step 1: Add the GridView to your page, placing it inside an UpdatePanel.


<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
             <ContentTemplate>
                 <asp:Label ID="lblTitle" runat="server" Text="User List" BackColor="lightblue" Width="95%" />
                 <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" Width="95%">
                     <AlternatingRowStyle BackColor="aliceBlue" />
                     <HeaderStyle HorizontalAlign="Left" />
                     <Columns>
                         <asp:BoundField DataField="ID" HeaderText="ID" />
                         <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                         <asp:BoundField DataField="LastName" HeaderText="LastName" />
                         <asp:BoundField DataField="Address" HeaderText="Address" />

                     </Columns>
                 </asp:GridView>
             </ContentTemplate>
         </asp:UpdatePanel>

Nothing out of the ordinary here, just a basic GridView contained in an UpdatePanel (don't forget to set UpdateMode to Conditional)

Step 2: Add a TemplateField with a Delete button.  Wire up an event handler for the button click.


<asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px" ItemStyle-HorizontalAlign="Center">
                             <ItemTemplate>
                                 <asp:Button ID="btnDelete" runat="server" OnClientClick="showConfirm(this); return false;"
                                     OnClick="BtnDelete_Click" Text="Delete" />
                             </ItemTemplate>
                         </asp:TemplateField>

You can either explicitly use the OnClick event of the delete button or add the CommandName attribute and implement the RowDeleting event. I chose the former for this sample.

Step 3: Add the HTML markup for the modal popup.

<div id=”div” runat=”server” align=”center” class=”confirm” style=”display:none”>
<img align=”absmiddle” src=”Img/warning.jpg” />Are you sure you want to delete this item?
<asp:Button ID=”btnOk” runat=”server” Text=”Yes” Width=”50px” />
<asp:Button ID=”btnNo” runat=”server” Text=”No” Width=”50px” />
</div>

Step 4: Add the ModalPopupExtender to the page.

<ajaxToolKit:ModalPopupExtender
runat=”server” BehaviorID=”mdlPopup”
TargetControlID=”div” PopupControlID=”div”
OkControlID=”btnOk” CancelControlID=”btnNo” BackgroundCssClass=”modalBackground”
/>

Step 5: Add an OnClientClick for the delete button

<asp:TemplateField ControlStyle-Width=”50px” HeaderStyle-Width=”60px” ItemStyle-HorizontalAlign=”Center”>
<ItemTemplate>
<asp:Button
ID=”btnDelete” runat=”server” OnClientClick=”showConfirm(this); return false;”
OnClick=”BtnDelete_Click” Text=”Delete” />
</ItemTemplate>
</asp:TemplateField>

Step 6: Add the supporting javascript

<script type=”text/javascript”>
// keeps track of the delete button for the row
// that is going to be removed
var _source;
// keep track of the popup div
var _popup;

function showConfirm(source){
this._source = source;
this._popup = $find(’mdlPopup’);

// find the confirm ModalPopup and show it
this._popup.show();
}

function okClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// use the cached button as the postback source
__doPostBack(this._source.name, ”);
}

function cancelClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// clear the event source
this._source = null;
this._popup = null;
}
</script>

Here is the complete listing for this page.

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!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 id="head" runat="server">
    <title>Delete Confirm Example</title>

    <script runat="server">

        public class User
        {
            private int _id;
            private string _firstName;
            private string _lastName;
            private string _Address;
            public User(int id, string firstname, string lastname, string address)
            {
                this._id = id;
                this._firstName = firstname;
                this._lastName = lastname;
                this._Address = address;
            }
            public int ID
            {
                get { return this._id; }
            }
            public string FirstName
            {
                get { return this._firstName; }
            }

            public string LastName
            {

                get { return this._lastName; }

            }
            public string Address
            {
                get { return this._Address; }
            }
        }
        private System.Collections.Generic.List<User> Users
        {
            get
            {
                System.Collections.Generic.List<User> item = this.Session["Users"] as System.Collections.Generic.List<User>;
                if (item == null)
                {
                    item = new System.Collections.Generic.List<User>();
                    item.Add(new User(1, "santosh", "kumar", "Chandigarh"));
                    item.Add(new User(2, "Vinod", "kumar", "HP"));
                    item.Add(new User(3, "Ajay", "Chawla", "PB"));
                    item.Add(new User(4, "MandeepInder", "Singh", "Chandigarh"));
                    this.Session["Users"] = item;
                }
                return item;
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.gvUsers.DataSource = this.Users;
                this.gvUsers.DataBind();
            }

        }

        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            //  get the gridviewrow from the sender so we can get the datakey we need
            Button btnDelete = sender as Button;
            GridViewRow row = (GridViewRow)btnDelete.NamingContainer;
            //  find the item and remove it
            User itemToRemove = this.Users[row.RowIndex];
            this.Users.Remove(itemToRemove);
            //  rebind the datasource
            this.gvUsers.DataSource = this.Users;
            this.gvUsers.DataBind();
        }

    </script>
    <script type="text/javascript">
     //  keeps track of the delete button for the row
     //  that is going to be removed
     var _source;
     // keep track of the popup div
     var _popup;
     function showConfirm(source){
         this._source = source;
         this._popup = $find('mdlPopup');
         //  find the confirm ModalPopup and show it 
         this._popup.show();
     }
     function okClick(){
         //  find the confirm ModalPopup and hide it 
         this._popup.hide();
         //  use the cached button as the postback source
         __doPostBack(this._source.name, '');

     }

     function cancelClick(){
         //  find the confirm ModalPopup and hide it
         this._popup.hide();
         //  clear the event source
         this._source = null;
         this._popup = null;

     }

    </script>
    <style>

     .modalBackground {

         background-color:Gray;

         filter:alpha(opacity=70);

         opacity:0.7;

     }

     .confirm{

        background-color:White;

        padding:10px;

        width:370px;

     }

 </style>
</head>
<body>
    <form id="form" runat="server" style="font-family: Trebuchet MS;">
        <asp:ScriptManager ID="scriptManager" runat="server" />
        <div>
            <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:Label ID="lblTitle" runat="server" Text="User List" BackColor="lightblue" Width="95%" />
                    <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" Width="95%">
                        <AlternatingRowStyle BackColor="aliceBlue" />
                        <HeaderStyle HorizontalAlign="Left" />
                        <Columns>
                            <asp:BoundField DataField="ID" HeaderText="ID" />
                            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                            <asp:BoundField DataField="LastName" HeaderText="LastName" />
                            <asp:BoundField DataField="Address" HeaderText="Address" />
                            <asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Button ID="btnDelete" runat="server" OnClientClick="showConfirm(this); return false;"
                                        OnClick="BtnDelete_Click" Text="Delete" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>
            <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" BehaviorID="mdlPopup" runat="server"
                TargetControlID="div" PopupControlID="div" OkControlID="btnOk" OnOkScript="okClick();"
                CancelControlID="btnNo" OnCancelScript="cancelClick();" BackgroundCssClass="modalBackground" />
            <div id="div" runat="server" align="center" class="confirm" style="display: none">
                <img align="absmiddle" src="Img/warning.jpg" />Are you sure you want to delete this
                item?
                <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
                <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
            </div>
        </div>
    </form>
</body>
</html>