Posted in ASP.Net

GridView inside another GridView in ASP.NET

 

In RowDataBound event of GridView, we find the inner GridView control after every row data bound and we bind the data to that inner GridView in order to achieve NestedGridView.
Design the GridView as per below.

Set the “AutoGenerateColumns” property of GridView to false. And place the chlid GridView in ItemTemplate of ‘asp:TemplateField’ tag of parent GridView. Write the code in RowDataBound event to find the inner GridView and assign data source to that inner control.

Steps to create NestedGridView in ASP.Net.

Step:1(Database Layer)

Create Database with the name “NestedGridView”  as following
Create Database NestedGridView

In that NestedGridView database create three(3) tables  as shown in below image.

 

Write the stored procedures(3) like below

i)
Create Procedure sp_GetFileDetails ( @FileId int )
As
Select * from tbl_Files where FileId = @FileId
ii)
Create procedure sp_GetFilesFromCart
As
Begin
Select * from tbl_Cart c inner join tbl_Files f on f.FileId = c.FileId
End
iii)

Create procedure sp_GetPrintSize
As
Select * from tbl_PrintSize



Step:2(DataAccessLayer And BusinessLogicLayer)

i) Write the DataAccessLayer like this.

ii) Business Logic Layer Class:

   1:  using System;
   2:  using System.Data;
   3:  using System.Data.SqlClient;
   4:   
   5:  public class BusinessLogicLayer
   6:  {
   7:      public static DataSet GetFilesFromCart()
   8:      {
   9:          try
  10:          {
  11:              SqlParameter[] p = new SqlParameter[0];
  12:              return DataAccessLayer.ExecuteDataSet
  13:                  (
  14:                  DataAccessLayer.GetConnectionString(), 
  15:                  CommandType.StoredProcedure, "[sp_GetFilesFromCart]", p
  16:                  );
  17:          }
  18:          catch (Exception ex) { throw new ArgumentException(ex.Message); }
  19:      }
  20:   
  21:      public static DataSet GetPrintSize()
  22:      {
  23:          try
  24:          {
  25:              SqlParameter[] p = new SqlParameter[0];
  26:              return DataAccessLayer.ExecuteDataSet
  27:                  (
  28:                  DataAccessLayer.GetConnectionString(), 
  29:                  CommandType.StoredProcedure, "sp_GetPrintSize", p
  30:                  );
  31:          }
  32:          catch (Exception ex)
  33:          {
  34:              throw new ArgumentException(ex.Message);
  35:          }
  36:      }
  37:   
  38:      public static DataSet GetFileDetails(int fileId)
  39:      {
  40:          try
  41:          {
  42:              SqlParameter[] p = new SqlParameter[1];
  43:              p[0] = new SqlParameter("@FileId", fileId);
  44:              return DataAccessLayer.ExecuteDataSet
  45:                  (
  46:                  DataAccessLayer.GetConnectionString(), 
  47:                  CommandType.StoredProcedure, "sp_GetFileDetails", p
  48:                  );
  49:          }
  50:          catch (Exception ex)
  51:          {
  52:              throw new ArgumentException(ex.Message);
  53:          }
  54:      }
  55:  }

Step:3(PresentationLayer)

Default.aspx Page Source Code:

   1:  GridView ID="GridView1" runat="server" 
   2:  AutoGenerateColumns="False" 
   3:  ShowHeader="true" Width="500px" 
   4:  onrowdatabound="GridView1_RowDataBound">
   5:  <Columns>
   6:   
   7:  TemplateField  ItemStyle-BorderStyle="None" 
   8:                   HeaderText="S No"  ItemStyle-Font-Bold="true">
   9:  <ItemTemplate>
  10:  <%# Container.DataItemIndex + 1  %>
  11:  </ItemTemplate>
  12:  TemplateField>
  13:   
  14:  TemplateField HeaderText="Selected Photos">
  15:  <ItemTemplate>
  16:  <table>
  17:  <tr>
  18:  <td valign="middle">
  19:  ImageButton ID="ImageButton1" Enabled="false"
  20:    CommandName="selectedimg" 
  21:    ImageUrl='<%# "~/Thumbnail.ashx?fileId="+Eval("FileId") %>'
  22:     CommandArgument='<%# Eval("FileId") %>' runat="server">
  23:  ImageButton>
  24:  </td>
  25:  </tr>
  26:  </table>
  27:  </ItemTemplate>
  28:  TemplateField>
  29:   
  30:  TemplateField HeaderText="Print Options">
  31:  <ItemTemplate>
  32:  <%--Start ChildGridView--%>
  33:  GridView ID="GridView2" runat="server" 
  34:  ShowHeader="true" Width="300px" AutoGenerateColumns="false">
  35:  <Columns>
  36:  TemplateField HeaderText="Qty">
  37:  <ItemTemplate>
  38:  TextBox ID="TextBox1" MaxLength="3" ValidationGroup="add"
  39:    Width="35" onkeydown="return CheckKeyCode()" runat="server">
  40:  </asp:TextBox>
  41:  </ItemTemplate>
  42:  TemplateField>
  43:   
  44:  <asp:TemplateField HeaderText="Size">
  45:  <ItemTemplate>
  46:  LinkButton ID="LinkButton1" ForeColor="AliceBlue" 
  47:  CommandName="lbtnsize" Enabled="false" Text='<%# Eval("SizeName") %>'
  48:  CommandArgument='<%# Eval("SizeId") %>' runat="server">
  49:  LinkButton>
  50:  </ItemTemplate>
  51:  </asp:TemplateField>
  52:  Qty)">
  53:  <ItemTemplate>
  54:  <asp:LinkButton ID="LinkButton2" ForeColor="AliceBlue"
  55:   Text='<%# Eval("Price") %>' Enabled="false" CommandName="lbtnprice"
  56:  CommandArgument='<%# Eval("SizeId") %>' runat="server">
  57:  </asp:LinkButton>
  58:  </ItemTemplate>
  59:  </asp:TemplateField>
  60:   
  61:  <asp:TemplateField HeaderText="TotalPrice">
  62:  <ItemTemplate>
  63:  <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
  64:  </ItemTemplate>
  65:  </asp:TemplateField>
  66:   
  67:  </Columns>
  68:  GridView>
  69:  <%--End ChildGridView--%>
  70:  </ItemTemplate>
  71:  </asp:TemplateField>
  72:   
  73:  </Columns>
  74:  GridView>



Default.aspx.cs Code:

   1:  using System;
   2:  using System.Data;
   3:  using System.Web.UI.WebControls;
   4:   
   5:  public partial class _Default : System.Web.UI.Page 
   6:  {
   7:      protected void Page_Load(object sender, EventArgs e)
   8:      {
   9:          if (!IsPostBack)
  10:          {
  11:              DataSet ds = BusinessLogicLayer.GetFilesFromCart();
  12:              GridView1.DataSource = ds;
  13:              GridView1.DataBind();
  14:          }
  15:      }
  16:   
  17:      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  18:      {
  19:          if (e.Row.RowType == DataControlRowType.DataRow)
  20:          {
  21:              GridView gv = (GridView)e.Row.FindControl("GridView2");
  22:              DataSet ds1 = BusinessLogicLayer.GetPrintSize();
  23:              ImageButton ib = (ImageButton)e.Row.FindControl("ImageButton1");
  24:              gv.DataSource = ds1;
  25:              gv.DataBind();
  26:          }
  27:      }
  28:  }

Thumbnail.ashx:
<%@ WebHandler Language=”C#” Class=”Thumbnail” %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
public class Thumbnail : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (context.Request.QueryString[“fileId”].ToString() == “”)
{ }
else
{
int fileId = Convert.ToInt32(context.Request.QueryString[“fileId”]);
if (fileId != 0)
{
DataSet ds = BOL.GetFileDetails(fileId);
if (ds.Tables[0].Rows[0][“FileContent”] != System.DBNull.Value)
{
byte[] image = (byte[])ds.Tables[0].Rows[0][“FileContent”];
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(image, 0, image.Length);
context.Response.Buffer = true;
if (image.Length != 0)
{
Bitmap loBMP = new Bitmap(ms);
int wid = loBMP.Width;
if (wid > 120) { wid = 120; }
int hei = loBMP.Height;
if (hei > 100) { hei = 100; }
Bitmap bmpOut = new Bitmap(wid, hei);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, wid, hei);
g.DrawImage(loBMP, 0, 0, wid, hei);
MemoryStream ms2 = new MemoryStream();
bmpOut.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bmpBytes = ms2.GetBuffer();
bmpOut.Dispose();
ms2.Close();
context.Response.Clear();
context.Response.BinaryWrite(bmpBytes);
context.Response.End();
}
ms.Dispose();
}
}
}
}
public bool IsReusable {
get {
return false;
}
}
}

Leave a comment