Skip to main content

GRIDVIEW GROUPING


When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using AJAX Collapsible Panel Extender Control.
Overview:
I am going to use Adventure Works as datasource. Every product in Production.Product table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to expand/collapse to look/hide the list of products belonging to each subcategory.
Database Connection
Added following entry under connectionStrings element in web.config.
<add name="Sql" connectionString="Data Source=(local);
Initial Catalog=AdventureWorksUser=testuserPassword=testuser;"
providerName="System.Data.SqlClient"/>
Page Design
Register the AjaxControlToolkit at the top of the page (or in the web.config for the whole project)
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added, and has to be included on every page where you wish to use AJAX functionality.
<asp:ToolkitScriptManager runat="server" ID="MainScriptManager" />
I am using SQLDataSource to load the products categories from database. The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. TheSelectCommand property specifies the SQL statement to execute to retrieve the data.
<asp:SqlDataSource ID="sqlDsSubCategories" runat="server" ConnectionString="<%$ ConnectionStrings:Sql %>"
    SelectCommand="Select ProductSubCategoryID, Name from
Production.ProductSubCategory">
</asp:SqlDataSource>
I am using AJAX Update Panel to enable partial postbacks to avoid flashing and flickering that occurs when an ASP.NET page posts back to the server and turn it into smooth, flicker-free updates.  Add a GridView control to the template content of the update panel, which will be used to display products subcategories. In order to bind the SQLDataSource created above to the grid, set the “DataSourceID” property of the GridView to “sqlDsSubCategories” (ID property value of SQLDataSource).  I have added an ItemTemplate to render all products related to subcategory.
<asp:UpdatePanel ID="pnlUpdate" runat="server">
    <ContentTemplate>
        <asp:GridView Width="60%" AllowPaging="True" ID="gvSubCategories"
                    AutoGenerateColumns="False"
                    GridLines="None"
                    PagerStyle-CssClass="pgr"
                    CssClass="mGrid"
                    DataSourceID="sqlDsSubCategories" runat="server"
                    ShowHeader="False"
                    OnRowCreated="gvSubCategories_RowCreated"
                    DataKeyNames="ProductSubCategoryID">
            <Columns>
                <asp:TemplateField>
                    <ItemStyle Width="200px" />
                    <ItemTemplate>
                        <asp:Panel ID="pnlSubCategories" runat="server">
                            <!--- Header Row-->
                        </asp:Panel>
                <asp:Panel ID="pnlProducts" runat="server">
                            <!--- Filtered Products by SubCategory-->
                        </asp:Panel>
                <asp:CollapsiblePanelExtender>
                  <!—different attributes -->
                </asp:CollapsiblePanelExtender>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
  </asp:UpdatePanel>
I have added pnlSubCategories panel to the ItemTemplate. This is our  header/seperator panel . This is the panel that will expand or collapse the pnlProductspanel on a click. This comprises of an ImageControl  “imgCollapsible “ which would hold Expand/Collapse images.  Depending upon the collapsible state of  the panel, it would show either collapse image or expand image.  I am also displaying the name of the current SubCategory in a span element.
<asp:Panel ID="pnlSubCategories" runat="server">
  <asp:Image ID="imgCollapsible" Style="margin-right:5px;" runat="server"/>
  <span>SubCategory: <%#Eval("Name")%></span>
</asp:Panel>
I have added another panel pnlProducts to the ItemTemplate. This is the Panel that would expand and collapses on clicking expand/collapse buttons onpnlSubCategories panel. I have added gvProducts gridview control to this panel. In this gridview control, we display all the products for the current subcategory. The datasource for this gridview is a SqlDataSource object  “sqlDsProducts” which would accept ProductSubCategoryID as the parameter. This parameter is set in the RowCreated event of the gvSubCategories.
<asp:SqlDataSource ID="sqlDsProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:Sql %>"
    SelectCommand="Select ProductID, Name, ProductNumber
                from Production.Product
                where ProductSubCategoryID = @ProductSubCategoryID">
    <SelectParameters>
        <asp:Parameter Name="ProductSubCategoryID" Type="String"
                      DefaultValue="" />
    </SelectParameters>
</asp:SqlDataSource>
<asp:Panel Style="margin-left: 20px; margin-right: 20px" ID="pnlProducts"
runat="server" Width="75%">
    <asp:GridView AutoGenerateColumns="False" CssClass="mGrid"
        ID="gvProducts" DataSourceID="sqlDsProducts"
        runat="server" EnableViewState="False"  GridLines="None"
        AlternatingRowStyle-CssClass="alt">
       <Columns>
            <asp:BoundField HeaderText="Product Name" DataField="Name"/>
            <asp:BoundField HeaderText="Product Number"
                            DataField="ProductNumber"/>
        </Columns>
    </asp:GridView>
</asp:Panel>
protected void gvSubCategories_RowCreated(object sender,
GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        SqlDataSource ctrl = e.Row.FindControl("sqlDsProducts")
                               as SqlDataSource;
        if (ctrl != null && e.Row.DataItem != null)
        {
            ctrl.SelectParameters["ProductSubCategoryID"].DefaultValue =
                gvSubCategories.DataKeys[e.Row.RowIndex].Value.ToString();
        }
    }
}
All that is left is to add collapsible behavior between pnlSubCategories  and pnlProducts using CollapsiblePanelExtender .  I have added a CollapsiblePanelExtender control to the ItemTemplate. I have Set the TargetControlID  property to pnlProducts and ExpandControlID/ CollapseControlID properties to “pnlSubCategories” header panel. Initially we would want to load the panel in expanded, so I have set the Collapsed property to false. For this example, I am disabling mouse over AutoExpand & AutoCollapse functionality.  Finally, I have set the ExpandedImage & CollapsedImage properties to the url’s of the images you wanted to be displayed.
<asp:CollapsiblePanelExtender ID="ctlCollapsiblePanel"
runat="Server"
TargetControlID="pnlProducts"
CollapsedSize="0" Collapsed="True"
ExpandControlID="pnlSubCategories" CollapseControlID="pnlSubCategories"
AutoCollapse="False" AutoExpand="False" ScrollContents="false"
ImageControlID="imgCollapsible"
ExpandedImage="~/collapse.gif" CollapsedImage="~/expand.gif"
ExpandDirection="Vertical" />
Run the application and you would notice al products are grouped by SubCategory and are in collapsed state. 
Click on expand images to unhide any subcategory group and look at all products belonging to that subcategory.
Complete Design
<asp:ToolkitScriptManager runat="server" ID="MainScriptManager" />
<asp:SqlDataSource ID="sqlDsSubCategories" runat="server"
    ConnectionString="<%$ ConnectionStrings:Sql %>"
    SelectCommand="Select ProductSubCategoryID, Name from Production.ProductSubCategory">
</asp:SqlDataSource>
<asp:UpdatePanel ID="pnlUpdate" runat="server">
    <ContentTemplate>
        <asp:GridView Width="45%" AllowPaging="True" ID="gvSubCategories"
                    AutoGenerateColumns="False"
                    GridLines="None"
                    CssClass="mGrid"
                    DataSourceID="sqlDsSubCategories" runat="server"
                    ShowHeader="False"
                    OnRowCreated="gvSubCategories_RowCreated"
                    DataKeyNames="ProductSubCategoryID">
            <Columns>
                <asp:TemplateField>
                    <ItemStyle Width="200px" />
                    <ItemTemplate>
                        <asp:Panel ID="pnlSubCategories" runat="server">
                            <asp:Image ID="imgCollapsible"
                                Style="margin-right: 5px;" runat="server" />
                             <span style="font-weight:bold">
                                    SubCategory: <%#Eval("Name")%>
                             </span>
                        </asp:Panel>
                      <asp:SqlDataSource ID="sqlDsProducts" runat="server"
                         ConnectionString="<%$ ConnectionStrings:Sql %>"
                   SelectCommand="Select ProductID, Name,
                             ProductNumber from Production.Product
                          where ProductSubCategoryID= @ProductSubCategoryID">
                          <SelectParameters>
                            <asp:Parameter Name="ProductSubCategoryID"
                                          Type="String"
                                          DefaultValue="" />
                            </SelectParameters>
                        </asp:SqlDataSource>
                        <asp:Panel ID="pnlProducts" runat="server"
                                   Width="75%"
                            Style="margin-left:20px;margin-right:20px;
                                   height:0px;overflow: hidden;">
                            <asp:GridView AutoGenerateColumns="False"
                                CssClass="mGrid" ID="gvProducts"
                                DataSourceID="sqlDsProducts"
                                runat="server" EnableViewState="False"
                                GridLines="None"
                                AlternatingRowStyle-CssClass="alt">
                               <Columns>
                                    <asp:BoundField HeaderText="Product Name"
                                              DataField="Name"/>
                                    <asp:BoundField
                                        HeaderText="Product Number"
                                        DataField="ProductNumber"/>
                                </Columns>
                            </asp:GridView>
                        </asp:Panel>
                        <asp:CollapsiblePanelExtender
                           ID="ctlCollapsiblePanel"
                            runat="Server"
                            TargetControlID="pnlProducts"
                            CollapsedSize="0" Collapsed="True"
                            ExpandControlID="pnlSubCategories"
                            CollapseControlID="pnlSubCategories"
                            AutoCollapse="False" AutoExpand="False"
                            ScrollContents="false"
                            ImageControlID="imgCollapsible"
                            ExpandedImage="~/collapse.gif"
                            CollapsedImage="~/expand.gif"
                            ExpandDirection="Vertical" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

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

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

Add Edit Update Records in GridView using Modal Popup in ASP.Net

Add Edit Update Records in GridView using Modal Popup in ASP.Net In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender. Database For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link. Download Northwind Database Connection string Below is the connection string to connect to the database. < connectionStrings >     < add name = " conString "      connectionString = " Data Source=.\SQLExpress;database=Northwind;     Integrated Security=true " /> </ connectionStrings >   HTML Markup Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView