Skip to main content

GridView nested inside another GridView in ASP.NET

Download Files:
 

Tables:

Create Database with the name as "NestedGridView" and create following tables in that database.

Tables.bmp
Stored Procedures:

Create Procedure sp_GetFileDetails
(
@FileId int
)
AS
Begin
select
* from tbl_Files where FileId = @FileId
End
Create procedure sp_GetFilesFromCart
As
begin
select
* from tbl_Cart c inner join tbl_Files f on
f.FileId = c.FileId
end
Create procedure sp_GetPrintSize
As
Begin
select
* from tbl_PrintSize
End

Web.config:

       <connectionStrings>
              <
add name="constr" connectionString="User Id = sa; Password = 123; Database = NestedGridView; Data Source = server2"/>
       </connectionStrings>
Classes:
1. Connection Class:
public class Connection
{
       public static string GetConnectionString()
    {
        return ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    }
}
2. Data Access Layer Class:
public class DAL
{
       static SqlConnection con;
    static SqlCommand cmd;
    static DataSet ds;
    static SqlDataAdapter da;
    public static DataSet ExecuteDataSet(string connectionString, CommandType commandType, string commandText,SqlParameter[] parameters)
    {
        try
        {
            con = new SqlConnection(connectionString);
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = commandText;
            cmd.CommandType = commandType;
            if (parameters == null)
            {
                da = new SqlDataAdapter(cmd);
                ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
            else
            {
                foreach (SqlParameter p in parameters)
                {
                    if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
                    {
                    }
                        cmd.Parameters.Add(p);
                }
                da = new SqlDataAdapter(cmd);
                ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
        }
        catch (SqlException ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }
}
3. Business Object Layer Class:
public class BOL
{
       public static DataSet GetFilesFromCart()
    {
        try
        {
            SqlParameter[] p = new SqlParameter[0];
            return DAL.ExecuteDataSet(Connection.GetConnectionString(), CommandType.StoredProcedure, "[sp_GetFilesFromCart]", p);
        }
        catch (Exception ex) { throw new ArgumentException(ex.Message); }
    }
    public static DataSet GetPrintSize()
    {
        try
        {
            SqlParameter[] p = new SqlParameter[0];
            return DAL.ExecuteDataSet(Connection.GetConnectionString(), CommandType.StoredProcedure, "sp_GetPrintSize", p);
        }
        catch (Exception ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }
    public static DataSet GetFileDetails(int fileId)
    {
        try
        {
            SqlParameter[] p = new SqlParameter[1];
            p[0] = new SqlParameter("@FileId", fileId);
            return DAL.ExecuteDataSet(Connection.GetConnectionString(), CommandType.StoredProcedure, "sp_GetFileDetails", p);
        }
        catch (Exception ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }
}
Default.aspx Page Source Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    ShowHeader="true" 
                     Width="500px"
                    onrowdatabound="GridView1_RowDataBound">
                <Columns>
               <asp:TemplateField  ItemStyle-BorderStyle="None" HeaderText="S No"  ItemStyle-Font-Bold="true">
                <ItemTemplate>
                <%# Container.DataItemIndex + 1  %>
                </ItemTemplate>
                </asp:TemplateField>
               <asp:TemplateField HeaderText="Selected Photos">
               <ItemTemplate>
                    <table>
               <tr>
               <td valign="middle">
               <asp:ImageButton ID="ImageButton1" Enabled="false"  CommandName="selectedimg" ImageUrl='<%# "~/Thumbnail.ashx?fileId="+Eval("FileId") %>' CommandArgument='<%# Eval("FileId") %>' runat="server">
                   </asp:ImageButton>
               </td>
               </tr>
               </table>
               </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="Print Options">
               <ItemTemplate>
                   <asp:GridView ID="GridView2" runat="server" ShowHeader="true" Width="300px" AutoGenerateColumns="false">
                   <Columns>
                   <asp:TemplateField HeaderText="Qty">
                   <ItemTemplate>
                   <asp:TextBox ID="TextBox1" MaxLength="3" ValidationGroup="add"  Width="35" onkeydown="return CheckKeyCode()" runat="server"></asp:TextBox>
                   </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="Size">
                   <ItemTemplate>
                   <asp:LinkButton ID="LinkButton1" ForeColor="AliceBlue" CommandName="lbtnsize" Enabled="false" Text='<%# Eval("SizeName") %>' CommandArgument='<%# Eval("SizeId") %>' runat="server"></asp:LinkButton>
                   </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="Price(1 Qty)">
                   <ItemTemplate>
                   <asp:LinkButton ID="LinkButton2" ForeColor="AliceBlue" Text='<%# Eval("Price") %>' Enabled="false" CommandName="lbtnprice" CommandArgument='<%# Eval("SizeId") %>' runat="server"></asp:LinkButton>
                   </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="TotalPrice">
                   <ItemTemplate>
                   <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
                   </ItemTemplate>
                   </asp:TemplateField>
                   </Columns>
                   </asp:GridView>
               </ItemTemplate>
               </asp:TemplateField>
                </Columns>
                </asp:GridView>
Default.aspx.cs CodeBehind:
protected void Page_Load(object sender, EventArgs e)    {
        if (!IsPostBack)
        {
            DataSet ds = BOL.GetFilesFromCart();
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView gv = (GridView)e.Row.FindControl("GridView2");
            DataSet ds1 = BOL.GetPrintSize();
            ImageButton ib = (ImageButton)e.Row.FindControl("ImageButton1");
            gv.DataSource = ds1;
            gv.DataBind();
        }
    }
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;
        }
    }
}

GridView.gif

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to solve this browser compatibility proble

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour