Wednesday, December 21

Collapsable nested GridView with paging

In this article we will explore how to do paging in nested collapsable gridview. In this gridview only one child gridview will be visible. One can collapse all the nested gridview, only parent gridview will be visible. The paging index of each child gridview will be retained. Update panel has been used to make the paging smooth and seemless.
NestedGridViewWithPaging


Let's see how we can do it.


Step 1: Add scriptmanager in the aspx page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods
="true"></asp:ScriptManager>

Step 2: Add a gridview with another gridview in the last templatefield. The last templatefield will also contain a label which will be used as last column in the parent gridview.Place both the gridview in the updatepanel.


<asp:UpdatePanel runat="server" ID="updTest">
      
<ContentTemplate
>
            
<asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvParent_RowDataBound" CellPadding="4" ForeColor="#333333" ShowHeader="True" DataKeyNames
="EmployeeId">
                  
<Columns
>
                        
<asp:TemplateField ItemStyle-Width
="20px">
                              
<ItemTemplate
>
                                    
<asp:Image runat="server" ID="img1" ImageUrl="images/Collapse.GIF"
/>
                              
</ItemTemplate
>
                        
</asp:TemplateField
>
                        
<asp:BoundField HeaderText="Employee Id" DataField
="EmployeeId">
                              
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
                        
</asp:BoundField
>
                        
<asp:BoundField HeaderText="Employee Name" DataField
="EmployeeName">
                              
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
                        
</asp:BoundField
>
                        
<asp:BoundField HeaderText="Designation" DataField
="Designation">
                              
<ItemStyle HorizontalAlign="Center" Width="140px"
/>
                        
</asp:BoundField
>
                        
<asp:TemplateField HeaderText
="Location">
                              
<ItemTemplate
>
                                    
<asp:Label ID="lblEmpName" runat="server" Text='<%# Eval("Location")%>'></asp:Label
>
                                    
<asp:Literal runat="server" ID="lit1" Text="</td><tr id="trCollapseGrid" style='display:none' ><td colspan='5'>"
/>
                                    
<asp:GridView ID="gvChild" AutoGenerateColumns ="False" runat="server" EnableViewState="False" DataKeyNames="EmployeeId" ForeColor="#333333" PageSize="1" AllowPaging="True" OnPageIndexChanging
="gvChild_PageIndexChanging">
                                          
<RowStyle BackColor="#EFF3FB"
/>
                                          
<AlternatingRowStyle BackColor="White"
/>
                                          
<Columns
>
                                                
<asp:BoundField HeaderText="Skill ID" DataField
="SkillID">
                                                      
<ItemStyle HorizontalAlign="Center" Width="80px"
/>
                                                
</asp:BoundField
>
                                                
<asp:BoundField HeaderText="Employee Id" DataField
="EmployeeId">
                                                      
<ItemStyle HorizontalAlign="Center" Width="100px"
/>
                                                
</asp:BoundField
>
                                                
<asp:BoundField HeaderText="Skill Set" DataField
="SkillSet">
                                                      
<ItemStyle HorizontalAlign="Center" Width="110px"
/>
                                                
</asp:BoundField
>
                                                
<asp:BoundField HeaderText="Remarks" DataField
="Remarks">
                                                      
<ItemStyle HorizontalAlign="Center" Width="245px"
/>
                                                
</asp:BoundField
>
                                          
</Columns
>
                                          
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"
/>
                                    
</asp:GridView
>
                                    
<asp:Literal runat="server" ID="lit2" Text="</td></tr>"
/>
                              
</ItemTemplate
>
                        
</asp:TemplateField
>
                  
</Columns
>
                  
<RowStyle BackColor="#EFF3FB"
/>
                  
<AlternatingRowStyle BackColor="White"
/>
            
</asp:GridView
>
      
</ContentTemplate
></asp:UpdatePanel>

Step 3: Add two hidden fields. hidRowId will be used to store the rowid of parent grid  hidImgId will be used to store the corresponding imageid of the image in the row.

<
asp:HiddenField ID="hidRowId" runat="server" /><asp:HiddenField ID="hidImgId" runat="server" />

Step 4: Add updateprogress on top of the update panel to give some animated effect.


<div style="height:20px">
      
<asp:UpdateProgress runat="server" ID
="PageUpdateProgress">
            
<ProgressTemplate
>
                  
<img src="images/processing.gif" alt="Processing"
/>
                  
Processing......
            </ProgressTemplate
>
      
</asp:UpdateProgress
></div>

Step 5: Add below javascript in the aspx page, it will be used to expand and collapse the child gridview.


<script language="javascript" type="text/javascript">function OpenTable(trRow, imgId) {
      object = document.getElementById(trRow);
      var rowId = document.getElementById('<%=hidRowId.ClientID %>'
).value;
      var imageId = document.getElementById('<%=hidImgId.ClientID %>'
).value;
      if (rowId != '
) {
            if (document.getElementById('<%=hidImgId.ClientID %>'
).value != imgId) {
                  document.getElementById(rowId).style.display = "none"
;
                  document.getElementById(imageId).src = "images/Collapse.gif"
;
            }
      }
      document.getElementById('<%=hidImgId.ClientID %>'
).value = imgId;
      document.getElementById('<%=hidRowId.ClientID %>'
).value = trRow;
      if (object.style.display == "none"
) {
            object.style.display = ""
;
            document.getElementById(imgId).src = "images/Expand.gif"
;
      }
      else
{
            object.style.display = "none"
;
            document.getElementById(imgId).src = "images/Collapse.gif"
;
      }
}

</script>

Step 6 Create a method GetParentTableData which will return datatable. Bind the datatable returned by GetParentTableData  with parent gridview on page load.


private DataTable GetParentTableData()
{
      DataTable table = new DataTable
();
      table.Columns.Add("EmployeeId", typeof(string
));
      table.Columns.Add("EmployeeName", typeof(string
));
      table.Columns.Add("Designation", typeof(string
));
      table.Columns.Add("Location", typeof(string
));

      table.Rows.Add(100, "Andy", "S/W Engg", "NY"
);
      table.Rows.Add(200, "James", "S/W Engg", "NJ"
);
      table.Rows.Add(300, "Ramesh", "Sr. S/W Engg", "Bangalore"
);
      table.Rows.Add(400, "George", "Architect", "London"
);
      table.Rows.Add(500, "Lisa", "Manager", "Washington"
);
      return
table;
}


protected void Page_Load(object sender, EventArgs e)
{

      
gvParent.DataSource = GetParentTableData();
      gvParent.DataBind();
      if
(!Page.IsPostBack)
      {
            GridViewChildPageIndex();
      }
}


Step 7: Create a method
GetChildTableData which will return datatable. The datatable returned by G
etChildTableData will bind to child gridview. EmployeeId of parent and childgridview will be same. It will act as foreign key.

private
DataTable GetChildTableData()
{
      DataTable table = new DataTable
();
      table.Columns.Add("SkillID", typeof(string
));
      table.Columns.Add("EmployeeId", typeof(string
));
      table.Columns.Add("SkillSet", typeof(string
));
      table.Columns.Add("Remarks", typeof(string
));
      table.Rows.Add("1", "100", "ASP.NET", "Remarks1"
);
      table.Rows.Add("2", "100", "SQL", "Remarks2"
);
      table.Rows.Add("1", "200", "ASP.NET", "Remarks1"
);
      table.Rows.Add("2", "200", "SQL", "Remarks2"
);
      table.Rows.Add("3", "200", "WCF"
"Remarks3"
);
      table.Rows.Add("4", "300", "PHP", "Remarks1"
);
      table.Rows.Add("5", "300", "Oracle", "Remarks2"
);
      table.Rows.Add("6", "300", "Javascipt", "Remarks3"
);
      table.Rows.Add("7", "400", "J2EE", "Remarks1"
);
      table.Rows.Add("5", "400", "Oracle", "Remarks2"
);
      table.Rows.Add("8", "400", "Struts", "Remarks3"
);
      table.Rows.Add("9", "500", "Estimation", "Remarks1"
);
      table.Rows.Add("10", "500", "Project Plan", "Remarks2"
);
      table.Rows.Add("11", "500", "Resource Loading", "Remarks3"
);
      table.Rows.Add("12", "500", "Resource allocation", "Remarks4"
);
      return
table;

}

Step 8:  Add gvParent_RowDataBound method, in this method the child grid view will be searched in the parent gridview and corresponding data will bind to it.


protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
      if (e.Row.RowType == DataControlRowType
.DataRow)      {            Image img = (Image)e.Row.Cells[0].FindControl("img1");            Literal ltrl = (Literal)e.Row.FindControl("lit1");            ltrl.Text = ltrl.Text.Replace("trCollapseGrid", "trCollapseGrid" + e.Row.RowIndex.ToString());
            
string str = "trCollapseGrid"
+ e.Row.RowIndex.ToString();
            e.Row.Cells[0].Attributes.Add(
"OnClick", "OpenTable('" + str + "','" + img.ClientID + "')"
);
            e.Row.Cells[0].RowSpan = 1;
            System.Web.UI.WebControls.
GridView gvChild = (System.Web.UI.WebControls.GridView)e.Row.FindControl("gvChild"
);
            
if (Session["ChildPageIndex"] != null
)            {                  DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];                  gvChild.PageIndex = Convert.ToInt16(dtPageIndex.Rows[e.Row.RowIndex][0]);            }            BindChildGrdView(gvParent.DataKeys[e.Row.RowIndex].Value.ToString(), gvChild);      }
}


Step 9: Add
gvChild_PageIndexChanging method which will provide functionality of pagin in child gridview. I have added System.Threading.Thread.Sleep to make it appear for some time. Remove it in real implementation in the application.

protected void gvChild_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
      System.Threading.
Thread
.Sleep(2000);      System.Web.UI.WebControls.GridView gvwChild = ((System.Web.UI.WebControls.GridView)sender);
      
GridViewRow gvRowParent = ((System.Web.UI.WebControls.GridView)sender).Parent.Parent as GridViewRow
;
      gvwChild.PageIndex = e.NewPageIndex;
      
if (Session["ChildPageIndex"] != null
)
      {
            
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"
];
            dtPageIndex.Rows[gvRowParent.RowIndex][0] = e.NewPageIndex;
      }
      BindChildGrdView(gvParent.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);
      
if (!ClientScript.IsStartupScriptRegistered("alert"
))
      {
            
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "document.getElementById('" + hidRowId.Value + "').style.display = ';", true
);
      }
}

Session has been used in gvParent_RowDataBound and gvChild_PageIndexChanging method to maintain the paging index of each child grid.


Step 10:
GridViewChildPageIndex method is used to set the pageindex to 0 in the session object.

private void GridViewChildPageIndex()
{
      
DataTable dtPageIndex = new DataTable
();
      dtPageIndex.Columns.Add(
"PageIndex", typeof(int
));
      
for (int
i = 0; i < gvParent.Rows.Count; i++)
      {
            dtPageIndex.Rows.Add(
"0"
);
      }
      Session[
"ChildPageIndex"
] = dtPageIndex;
}

Step 11:
BindChildGrdView will bind the data to the child gridview.


private void BindChildGrdView(string empId, System.Web.UI.WebControls.GridView gvChild)
{
      DataTable
dtChildTable = GetChildTableData();
      DataTable
dtCloneChildTable = dtChildTable.Clone();
      DataRow[] gvChildRows = dtChildTable.Select("EmployeeId = "
+ empId);
      foreach (DataRow gvChildRow in
gvChildRows)
      {
            dtCloneChildTable.ImportRow(gvChildRow);
      }
      gvChild.DataSource = dtCloneChildTable;
      gvChild.DataBind();
}

This ends the article of paging in nested gridview.
Live Demo 

Download Code
Thanks
    shibashish mohanty

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty