Search...

Friday, February 24, 2012

Gridview inside a GridView



********************************************************************************


/*Add Stylesheet in your application names StyleSheet.css*/
body {}
.gridView{width:100%;background:#ffffff;border:1px solid #476db6; border-collapse:separate;}
.gridView th{border:0px;background:#a7b7fe;color:#000000;text-align:center;font-size:18px;}
.gridView td{border:0px;padding-left:10px;}
.altRow{background:#d1daff;}
.gridPager{background:#a7b7fe;color:#000000;}
.gridPager table{margin:0px auto;}
.gridPager table td{width:20px;}
.gridPager table span{cursor:pointer;font-weight:bold;color:#1a1ac9;}
.gridPager table a{cursor:pointer;text-decoration:none;color:#000000;}
.gridPager table a:hover{text-decoration:underline;}


********************************************************************************

<%@ 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 id="Head1" runat="server">
    <title>Gridview inside a GridView</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>

     <asp:GridView ID="OuterGrid"
        runat="server"
        DataKeyNames="Id"
        AutoGenerateColumns="false"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager" onrowdatabound="OuterGrid_RowDataBound"
        >
    <Columns>
        <asp:TemplateField HeaderText="Department Name">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Departmentname") %>' />
        </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField>
        <ItemTemplate>
            <asp:GridView ID="InnerGrid"
            runat="server"
            AutoGenerateColumns="false"
            CssClass="gridView"
            AlternatingRowStyle-CssClass="altRow">
            <Columns>
            <asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
            <asp:BoundField DataField="Salary" HeaderText="Salary" />
            </Columns>
            </asp:GridView>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
</div>
    </form>
</body>
</html>

********************************************************************************

using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindOuterGrid();
        }
        OuterGrid.CellSpacing = 1;
    }
    
    public void BindOuterGrid()
    {
        Department department = new Department();
        OuterGrid.DataSource = department.ReadAll();
        OuterGrid.DataBind();
    }
    protected void OuterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Employee employee = new Employee();
            GridViewRow currentRow = e.Row;
            String dataKey=OuterGrid.DataKeys[currentRow.RowIndex].Value.ToString();
            
            GridView innerGrid = (GridView)currentRow.Cells[1].FindControl("InnerGrid");
            innerGrid.DataSource = employee.ReadAllEmployeeByDepartment_id(dataKey);
            innerGrid.DataBind();
            innerGrid.CellSpacing = 1;
        }
    }
}

********************************************************************************
/*  Connection Class*

using System;
using System.Web.Configuration;
public class Connection
{
public Connection(){}
     /// <summary>
     /// Get Connection string.
     /// <summary>
  public static String Cs
    {
        get
        {
            return WebConfigurationManager.ConnectionStrings["cs"].ConnectionString;
        }
    }
}

********************************************************************************
/* Department Class*/

#region Namespaces

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
#endregion

/// <summary>
/// class Department
/// </summary>
 public class Department
 {
#region Properties
      private Int32 _Id;
     /// <summary>
     ///Gets or Sets the Int32 value of Id
     /// </summary>
      public Int32 Id { get { return _Id;} set { _Id = value;} }

      private String _Departmentname;
     /// <summary>
     ///Gets or Sets the String value of Departmentname
     /// </summary>
      public String Departmentname { get { return _Departmentname;} set { _Departmentname = value;} }

#endregion

#region Private Meambers
      private SqlCommand cmd;
      private SqlConnection con;
      private SqlDataReader table;
      private String ConnectionString = String.Empty;
#endregion

#region Constructor
     /// <summary>
     ///Default constructor 
     /// </summary>
      public Department()
      {
        ConnectionString=Connection.Cs;
      }

     /// <summary>
     ///Parameterised constructor 
     /// </summary>
      public Department(String connectionString)
      {
        ConnectionString=connectionString;
      }
#endregion

#region Public Methods

     /// <summary>
     /// This meathod returns all records of Department table.
     /// </summary>
     /// <returns> All rows of Department table.</returns>


      public List<Department> ReadAll()
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Department> list = new List<Department>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Department]",con);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Department obj = new Department();
                obj._Id = table.GetInt32(0);
                obj._Departmentname = table.GetString(1);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

     /// <summary>
     /// This meathod returns all records of Department table by column Id.
     /// </summary>
     /// <param name="Id"></param>
     /// <returns>All rows of Department table.</returns>


      public List<Department> ReadAllById(String id)
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Department> list = new List<Department>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Department] Where [Id]=@ID",con);
            cmd.Parameters.AddWithValue("@Id",id);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Department obj = new Department();
                obj._Id = table.GetInt32(0);
                obj._Departmentname = table.GetString(1);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

#endregion

 }

*********************************************************************************
/*Employee Class*/

#region Namespaces

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
#endregion

/// <summary>
/// class Employee
/// </summary>
 public class Employee
 {
#region Properties
      private Int32 _Id;
     /// <summary>
     ///Gets or Sets the Int32 value of Id
     /// </summary>
      public Int32 Id { get { return _Id;} set { _Id = value;} }

      private String _Employeename;
     /// <summary>
     ///Gets or Sets the String value of Employeename
     /// </summary>
      public String Employeename { get { return _Employeename;} set { _Employeename = value;} }

      private Decimal _Salary;
     /// <summary>
     ///Gets or Sets the Decimal value of Salary
     /// </summary>
      public Decimal Salary { get { return _Salary;} set { _Salary = value;} }

      private Int32 _Department_id;
     /// <summary>
     ///Gets or Sets the Int32 value of Department_id
     /// </summary>
      public Int32 Department_id { get { return _Department_id;} set { _Department_id = value;} }

#endregion

#region Private Meambers
      private SqlCommand cmd;
      private SqlConnection con;
      private SqlDataReader table;
      private String ConnectionString = String.Empty;
#endregion

#region Constructor
     /// <summary>
     ///Default constructor 
     /// </summary>
      public Employee()
      {
        ConnectionString=Connection.Cs;
      }

     /// <summary>
     ///Parameterised constructor 
     /// </summary>
      public Employee(String connectionString)
      {
        ConnectionString=connectionString;
      }
#endregion

#region Public Methods

     /// <summary>
     /// This meathod returns all records of Employee table.
     /// </summary>
     /// <returns> All rows of Employee table.</returns>


      public List<Employee> ReadAll()
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Employee> list = new List<Employee>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select Top(1000)* From [dbo].[Employee]",con);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Employee obj = new Employee();
                obj._Id = table.GetInt32(0);
                obj._Employeename = table.GetString(1);
                obj._Salary = table.GetDecimal(2);
                obj._Department_id = table.GetInt32(3);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

      /// <summary>
      /// This meathod returns all records of Employee table by column Department_id.
      /// </summary>
      /// <param name="Department_id" ></param>
      /// <returns>All rows of Employee table.</returns>


      public List<Employee> ReadAllEmployeeByDepartment_id(String department_id)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  List<Employee> list = new List<Employee>();
                  con = new SqlConnection(ConnectionString);
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Select * From [dbo].[Employee] where [Department_id]=@Department_id", con);
                  cmd.Parameters.AddWithValue("@Department_id", department_id);
                  using (table = cmd.ExecuteReader())
                  {
                      while (table.Read())
                      {
                          Employee obj = new Employee();
                          obj._Id = table.GetInt32(0);
                          obj._Employeename = table.GetString(1);
                          obj._Salary = table.GetDecimal(2);
                          obj._Department_id = table.GetInt32(3);
                          list.Add(obj);
                      }
                      //return (list.Count > 0) ? list : GetEmptyList(list);
                      return list;
                  }
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
              }
          }
      }

     /// <summary>
     /// This meathod is for updating record in Employee table by column Id.
     /// </summary>
     /// <param name="object of Employee"></param>
     /// <returns>Number of row affected by query.</returns>


      public Int32 UpdateById(Employee obj)
       {
        using(con = new SqlConnection(ConnectionString))
        {
         try
          {
           if (con.State == ConnectionState.Closed)
           {
             con.Open();
           }
           cmd = new SqlCommand("Update [dbo].[Employee] Set [Employeename] = @Employeename,[Salary] = @Salary,[Department_id] = @Department_id Where [Id] =@Id",con);
           cmd.Parameters.AddWithValue("@Employeename",obj._Employeename);
           cmd.Parameters.AddWithValue("@Salary",obj._Salary);
           cmd.Parameters.AddWithValue("@Department_id",obj._Department_id);
           cmd.Parameters.AddWithValue("@Id",obj._Id);
           return cmd.ExecuteNonQuery();
          }
         finally
          {
           if (con.State == ConnectionState.Open)
           {
             con.Close();
           }
           cmd.Parameters.Clear();
          }
        }
       }

     /// <summary>
     /// This meathod is for deleting records in Employee table by column Id.
     /// </summary>
     /// <param name="Id" ></param>
     /// <returns>Number of row affected by query.</returns>


      public Int32 DeleteById(String id)
       {
        using(con = new SqlConnection(ConnectionString))
        {
         try
          {
           if (con.State == ConnectionState.Closed)
           {
             con.Open();
           }
           cmd = new SqlCommand("Delete From [dbo].[Employee] Where [Id] =@Id",con);
           cmd.Parameters.AddWithValue("@Id",id);
           return cmd.ExecuteNonQuery();
          }
         finally
          {
           if (con.State == ConnectionState.Open)
           {
             con.Close();
           }
           cmd.Parameters.Clear();
          }
        }
       }
#endregion

 }

********************************************************************************* 
<connectionStrings>
<add name="cs" connectionString="Data Source=Your Data Source;Initial Catalog=softwarekaffee;Persist Security Info=True;User ID=sa;Password=Your Password"/>
</connectionStrings>

********************************************************************************* 
/*Database Schema*/

Go
Create database softwarekaffee

Go
use softwarekaffee 

Go
create table Department
(
Id int identity primary key,
DepartmentName nvarchar(30)
)
Insert Into Department Values ('Sales');
Insert Into Department Values ('Production');
Insert Into Department Values ('Purchase');
Insert Into Department Values ('Stock');

Go
create table Employee
(
Id int identity primary key,
EmployeeName nvarchar(30),
Salary decimal(7,2),
Department_Id int references Department(Id)
)

Insert Into Employee Values ('Kaushik',41000,1);
Insert Into Employee Values ('Rahul',25000,2);
Insert Into Employee Values ('Sumit',26000,3);
Insert Into Employee Values ('Ravi',40000,4);
Insert Into Employee Values ('Rajeev',41000,1);
Insert Into Employee Values ('Amit',25000,2);
Insert Into Employee Values ('Gautam',26000,3);
Insert Into Employee Values ('Ranveer',40000,4);
Insert Into Employee Values ('Devendra',40000,4);
Insert Into Employee Values ('Sunil',40000,4);

No comments: