Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Article

GridView within GridView

Rate me:
Please Sign up or sign in to vote.
2.85/5 (14 votes)
15 Jan 2008CPOL2 min read 99.9K   45   18
Manipulating ChildGrid within MasterGrid

Introduction

Hello, readers.

While building a web project, we may often come across the situation of displaying records or other types of data. We can do it in the best way by using DataGrid/GridView. It's very simple and requires only a knowledge of C#, of web application building and of SQL 2005.

"A picture is worth 1000 words!!" so I have explained a lot of things using pictures. I hope you will find it really easy. This is roughly what the final result looks like...

10.JPG

Design Info

First of all is the MasterGrid. You can design it as...

4.JPG

It has two columns, as shown. Here's a description of column zero...

3.JPG

Label1 is databound to Emp_dept_name, which I have described after the design info. MasterGrid column[1] can be designed as...

5.JPG

In ItemTemplate we have the ChildGrid. All the columns are template columns that contain a label (individually bound to fields in Emp_table, which is also described after the design info, as per the column name) in their ItemTemplate. All the columns have TextBoxes in their FooterTemplate. These are exposed when the New (in the Modify column) button is clicked. A Modify column that will be visible only when the Edit button in the 0th column of MasterGrid is clicked can be designed as...

6.JPG

I think that's sufficient to let you design all that is required.

NOTE: The DataKeyNames property of MasterGrid is set to Emp_dept_name.

Data Source

For the data I have used, see the two data tables Emp_table and Emp_dept, which you can create in SQL looking at the picture below...

9.JPG
8.JPG

You can execute these queries. In which case, choose the database name first.

30.JPG

I have used an SQL procedure...

7.JPG

You can save this using the procedure name (BindMasterGrid) itself.

NOTE: I have used two different tables. The databound <Label1> in the Department column is bound to Emp_dept_name in the Emp_dept table. For the rest of the work, Emp_table is used.

Using the Code

Coming to the coding part: don't forget to use the correct database connection string. Put it as a parameter at the time of declaring the SQL connection. Also, make sure that the web.config file contains the correct connection string.

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
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 _Default : System.Web.UI.Page 
{
    SqlConnection con=new SqlConnection ("
        Your database connection string here(
        under which you create Emp_table,Emp_dept tables)");
    DataView dv=new DataView();
    
    //
    //
    //*******************Use of dataview to be noted here*************************
    //
    //
    
    protected void Page_Load(object sender, EventArgs e)
    {
        dv = ((DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty));
        Page.MaintainScrollPositionOnPostBack = true;
        if (!Page.IsPostBack)
        {
            BindMasterGrid();
            BindChildGrid();
            
        }
    }
    
    //
    //To bind MasterGrid the use of strored procedure named-----BindMasterGrid----
    //
    //

    private void BindMasterGrid()
    {
        SqlCommand cmd = new SqlCommand("BindMasterGrid",con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds);

        MasterGrid.DataSource = ds;
        MasterGrid.DataBind();
        
    }

    //Before the GridView control can be rendered, each row in the control must be 
    //bound to a record in the data source.The RowDataBound event is raised when a
    //data row (represented by a GridViewRow object)is bound to data in the GridView 
    //control.
  
    protected void MasterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gr;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            gr = ((GridView)e.Row.FindControl("ChildGrid"));
            dv.RowFilter = "Emp_dept=" + Convert.ToString(
                MasterGrid.DataKeys[e.Row.RowIndex].Value);
            gr.DataSource = dv;
            gr.DataBind();
        }
    }

    //
    //Use of Select statement to bind the ChildGrid
    //
    //

    private void BindChildGrid()
    {

        for (int i = 0; i < MasterGrid.Rows.Count; i++)
        {

            ((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataSource = null;
            Label lbl1 = (Label)(MasterGrid.Rows[i].Cells[0].Controls[3]);
            DataSet ds1 = new DataSet();
            SqlCommand cmd = 
                new SqlCommand(
                "SELECT Emp_no, Emp_name, Emp_sal FROM Emp_table where Emp_dept ='" + 
                lbl1.Text + "'", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
            da.Fill(ds1, "Emp_table");
            ((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataSource = ds1;
            ((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).AllowSorting = true;
            ((GridView)MasterGrid.Rows[i].Cells[1].Controls[1]).DataBind();

        }
    }

    //
    //The event below is fired when "Edit" button in Department column is clicked
    //
    //The point to be noted here is that----we store the index of the row in which
    //Edit button was clicked----using Sessions.
    //
    //Modify column in the ChildGrid apears
    //

    protected void MasterGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {  
        int indx = e.NewEditIndex;
        Session["ind"] = indx;

        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        Childgrid.Columns[3].Visible = true;
        MasterGrid.Rows[i].FindControl("CancelMaster").Visible = true;

    }
20.JPG
C#
    //
    //The event below is fired when "Edit" button in Modify column of CildGrid is clicked
    //
    //

    protected void ChildGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int i = (int)Session["ind"]; 
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        
        Childgrid.EditIndex = e.NewEditIndex;
        BindChildGrid();    
    }
    
    //
    //The event below is fired when "Cancel" button in Department column is clicked
    //
    //

    protected void MasterGrid_RowCancelingEdit(
        object sender, GridViewCancelEditEventArgs e)
    {
        int i = (int)Session["ind"];
        MasterGrid.Rows[i].FindControl("CancelMaster").Visible = false;
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        Childgrid.Columns[3].Visible = false;
        Childgrid.EditIndex = -1;
        BindMasterGrid();
        BindChildGrid();

    }

    //
    //The event below is fired when "Cancel" button in 
    //Modify column(ChildGrid) is clicked
    //

    protected void ChildGrid_RowCancelingEdit(object sender, 
        GridViewCancelEditEventArgs e)
    {
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        Childgrid.EditIndex = -1;
        BindChildGrid();
        
    }

    //
    //To update the editing done in the ChildGrid 
    //
    //

    protected void ChildGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        
        int empno = 
            Convert.ToInt16(((Label)Childgrid.Rows[e.RowIndex].FindControl(
            "Label1")).Text);
        string empname = 
            ((TextBox)Childgrid.Rows[e.RowIndex].FindControl("TextBox2")).Text;
        double salary = 
            Convert.ToDouble(((
            TextBox)Childgrid.Rows[e.RowIndex].FindControl("TextBox3")).Text);
        
        SqlCommand cmd = 
            new SqlCommand("Update Emp_table set Emp_name='" + 
            empname + "',Emp_sal='" + salary +"'where Emp_no='" + empno+"'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Childgrid.EditIndex = -1;
        BindChildGrid();

    }

    //
    //Delete button will fire event below to delete a row in ChildGrid
    //
    //

    protected void ChildGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        int empno = 
            Convert.ToInt16(((Label)Childgrid.Rows[e.RowIndex].FindControl(
            "Label1")).Text);
        SqlCommand cmd = 
            new SqlCommand("Delete from Emp_table where Emp_no='" + empno + "'", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Childgrid.EditIndex = -1;
        BindChildGrid();

    }
 
    //
    //
    //Add a record in selected department
    //

    protected void Add_Click(object sender, EventArgs e)
    {
        
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);
        int empno = 
            Convert.ToInt16(((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Text);
        string empname = ((TextBox)Childgrid.FooterRow.FindControl("TextBox5")).Text;
        double salary = 
            Convert.ToDouble(((
            TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Text);
        string deptname = ((Label)MasterGrid.Rows[i].FindControl("Label1")).Text;
        SqlCommand cmd = 
            new SqlCommand("Insert into Emp_table values('" + 
            empno + "','" + empname + "','" + deptname + "','" + salary + "')", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        BindChildGrid();
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = false;
        ((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = false;
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = false;

    }

    //
    //New button is used to Expose TextBoxes to Enter new record
    //
    //

    protected void New_Click(object sender, EventArgs e)
    {
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

        BindChildGrid();
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = true;
        ((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = true;
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = true;
        ((LinkButton)Childgrid.FooterRow.FindControl("New")).Visible = false;
        ((LinkButton)Childgrid.FooterRow.FindControl("Add")).Visible = true;
        ((LinkButton)Childgrid.FooterRow.FindControl("Cancel")).Visible = true;
    }
    
    //
    //When Cancel button in Modify column is clicked
    //
    //
    
    protected void Cancel_Click(object sender, EventArgs e)
    {
        int i = (int)Session["ind"];
        GridView Childgrid = (GridView)(MasterGrid.Rows[i].Cells[1].Controls[1]);

        BindChildGrid();
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox4")).Visible = false;
        ((TextBox)Childgrid.FooterRow.FindControl("TExtBox5")).Visible = false;
        ((TextBox)Childgrid.FooterRow.FindControl("TextBox6")).Visible = false;
        ((LinkButton)Childgrid.FooterRow.FindControl("New")).Visible = true;
        ((LinkButton)Childgrid.FooterRow.FindControl("Add")).Visible = false;
        ((LinkButton)Childgrid.FooterRow.FindControl("Cancel")).Visible = false;
    }
}

Conclusion

I found it very interesting working with grids. We can extend this by further inserting a grid within a grid, although in real use we include various other features like JavaScript, etc. so as to avoid the transfer of bulk again and again over the web. There might be many other ways to do this efficiently, but as I am also at a beginner level, it will be best to start with this. I welcome any queries and responses from your side. Keep on making sincere efforts and you will be a good programmer one day.

Thanking you all,

HARSH BABBAR

History

  • 15 January, 2008 -- Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionaspx Pin
Member 1081305911-Aug-14 4:56
Member 1081305911-Aug-14 4:56 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey24-Feb-12 1:55
professionalManoj Kumar Choubey24-Feb-12 1:55 
QuestionASPX file Pin
Andrew Mundell28-Oct-11 5:32
Andrew Mundell28-Oct-11 5:32 
GeneralMy vote of 4 Pin
Dr.M.MANIKANDAN25-Aug-11 23:41
Dr.M.MANIKANDAN25-Aug-11 23:41 
Question.aspx file Pin
Member 791531217-Aug-11 16:50
Member 791531217-Aug-11 16:50 
AnswerSend aspx files too [modified] Pin
Member 385533016-Aug-11 7:59
Member 385533016-Aug-11 7:59 
GeneralASPX file Pin
Member 27062763-Jan-11 9:57
Member 27062763-Jan-11 9:57 
GeneralMy vote of 5 Pin
poojafhf25-Nov-10 17:56
poojafhf25-Nov-10 17:56 
GeneralASPX Code Pin
Binay Prasad14-Jun-10 0:15
Binay Prasad14-Jun-10 0:15 
GeneralAspx file Pin
Binay Prasad10-Jun-10 23:43
Binay Prasad10-Jun-10 23:43 
QuestionAspx file? Pin
hvap10-Nov-08 6:45
hvap10-Nov-08 6:45 
GeneralGridview with parameters Pin
Pwilson12-Oct-08 8:53
Pwilson12-Oct-08 8:53 
General.aspx file Pin
krkr10-Apr-08 5:55
krkr10-Apr-08 5:55 
GeneralRe: .aspx file Pin
babbar11-Apr-08 7:09
babbar11-Apr-08 7:09 
GeneralToo many database trips Pin
MKauffman16-Jan-08 6:46
MKauffman16-Jan-08 6:46 
GeneralRe: Too many database trips Pin
babbar16-Jan-08 7:21
babbar16-Jan-08 7:21 
GeneralRe: Too many database trips Pin
tparsnick5-Mar-08 14:43
tparsnick5-Mar-08 14:43 
GeneralRe: Too many database trips Pin
jennyfabia20-Jan-13 21:02
jennyfabia20-Jan-13 21:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.