Introduction
In this article, I will explain how to implement a grouping and calculate subtotal and a grand total for each group in ASP.Net GridView. To do this I used the RowCreated and RowDatabound events of a GridView. I used an XML file as the data source.
Objective
To understand grouping in an ASP.Net GridView.
Using code
UI
Items are grouped based on the customer name. For each customer, a total has been calculated and at the end a grand total has been calculated.
CODE
The main logic is in the RowCreated and RowDataBound events of the GridView. While iterating through all the rows I am catching the customer id and checking the other rows. When the customer id has been changed I am displaying the subtotal and resetting the subtotal. In the same way I am calculating the grand total. To display in a group format I am adding one row in a GridView once the customer id has been changed. In this row I display the subtotal. To display the heading I am adding a new row to the GridView. Please refer to the attachment to see the complete code.
Design
In design I just bound XML data source attributes. Please refer attachment to see complete code.
<asp:GridView ID="grdViewOrders" CssClass="serh-grid" runat="server" AutoGenerateColumns="False"
TabIndex="1" Width="100%" CellPadding="4" ForeColor="Black" GridLines="Vertical"
OnRowDataBound="grdViewOrders_RowDataBound" OnRowCommand="grdViewOrders_RowCommand"
OnRowCreated="grdViewOrders_RowCreated" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID" SortExpression="OrderID">
</asp:BoundField>

M Abrar ChughtaiPosted Sep 9, 2023, 5:43 AM
I have tried this code by changing CustomerID and CustomerName with ProductID and ProductName
M Abrar ChughtaiPosted Sep 9, 2023, 5:42 AM
Protected void grdViewOrders_RowCreated(object sender, GridViewRowEventArgs e) { bool IsSubTotalRowNeedToAdd = false; bool IsGrandTotalRowNeedtoAdd = false; if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "ProductID") != null)) if (strPreviousRowID != DataBinder.Eval(e.Row.DataItem, "ProductID").ToString()) IsSubTotalRowNeedToAdd = true; if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "ProductID") == null)) { IsSubTotalRowNeedToAdd = true; IsGrandTotalRowNeedtoAdd = true; intSubTotalIndex = 0; } #region Inserting first Row and populating fist Group Header details if ((strPreviousRowID == string.Empty) && (DataBinder.Eval(e.Row.DataItem, "ProductID") != null)) { GridView grdViewOrders = (GridView)sender; GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert); TableCell cell = new TableCell(); cell.Text = "ProductName : " + DataBinder.Eval(e.Row.DataItem, "ProductName").ToString(); cell.ColumnSpan = 6; cell.CssClass = "GroupHeaderStyle"; row.Cells.Add(cell); grdViewOrders.Controls[0].Controls.AddAt(e.Row.RowIndex + intSubTotalIndex, row); intSubTotalIndex++; } #endregion if (IsSubTotalRowNeedToAdd) { #region Adding Sub Total Row GridView grdViewOrders = (GridView)sender; // Creating a Row GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert); //Adding Total Cell TableCell cell = new TableCell(); cell.Text = "Sub Total"; cell.HorizontalAlign = HorizontalAlign.Left; cell.ColumnSpan = 2; cell.CssClass = "SubTotalRowStyle"; row.Cells.Add(cell); //Adding Unit Price Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblSubTotalUnitPrice); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "SubTotalRowStyle"; row.Cells.Add(cell); //Adding Quantity Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblSubTotalQuantity); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "SubTotalRowStyle"; row.Cells.Add(cell); //Adding Discount Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblSubTotalDiscount); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "SubTotalRowStyle"; row.Cells.Add(cell); //Adding Amount Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblSubTotalAmount); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "SubTotalRowStyle"; row.Cells.Add(cell); //Adding the Row at the RowIndex position in the Grid grdViewOrders.Controls[0].Controls.AddAt(e.Row.RowIndex + intSubTotalIndex, row); intSubTotalIndex++; #endregion #region Adding Next Group Header Details if (DataBinder.Eval(e.Row.DataItem, "ProductID") != null) { row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert); cell = new TableCell(); cell.Text = "ProductName : " + DataBinder.Eval(e.Row.DataItem, "ProductName").ToString(); cell.ColumnSpan = 6; cell.CssClass = "GroupHeaderStyle"; row.Cells.Add(cell); grdViewOrders.Controls[0].Controls.AddAt(e.Row.RowIndex + intSubTotalIndex, row); intSubTotalIndex++; } #endregion #region Reseting the Sub Total Variables dblSubTotalUnitPrice = 0; dblSubTotalQuantity = 0; dblSubTotalDiscount = 0; dblSubTotalAmount = 0; #endregion } if (IsGrandTotalRowNeedtoAdd) { #region Grand Total Row GridView grdViewOrders = (GridView)sender; // Creating a Row GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert); //Adding Total Cell TableCell cell = new TableCell(); cell.Text = "Grand Total"; cell.HorizontalAlign = HorizontalAlign.Left; cell.ColumnSpan = 2; cell.CssClass = "GrandTotalRowStyle"; row.Cells.Add(cell); //Adding Unit Price Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblGrandTotalUnitPrice); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "GrandTotalRowStyle"; row.Cells.Add(cell); //Adding Quantity Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblGrandTotalQuantity); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "GrandTotalRowStyle"; row.Cells.Add(cell); //Adding Discount Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblGrandTotalDiscount); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "GrandTotalRowStyle"; row.Cells.Add(cell); //Adding Amount Column cell = new TableCell(); cell.Text = string.Format("{0:0.00}", dblGrandTotalAmount); cell.HorizontalAlign = HorizontalAlign.Right; cell.CssClass = "GrandTotalRowStyle"; row.Cells.Add(cell); //Adding the Row at the RowIndex position in the Grid grdViewOrders.Controls[0].Controls.AddAt(e.Row.RowIndex, row); #endregion } }
M Abrar ChughtaiPosted Sep 9, 2023, 5:39 AM
I want to group by on the base of product name.
Jorge E. SomersPosted Jan 29, 2022, 4:48 PM
Hi I made some improvements which I?d like to send to you... drop me a letter [email protected]
Akhilesh BhartiPosted Jun 17, 2021, 7:23 AM
Great effort. Got it to work with some changes according to my data. Only problem is it is not showing the Totals for Last Group. Kindly help.
Imran AliPosted Mar 16, 2021, 3:40 PM
How to do same functionality with jquery datatable with row edit option?
Lee SochiaPosted Sep 1, 2019, 6:35 PM
Prabhat, Your GridView grouping is exactly what I need, unfortunately my project is in VB... back to the drawing board.
Habibur RahmanPosted Aug 30, 2019, 1:15 AM
Very nice work
shekhar kumarPosted Jul 25, 2019, 5:56 AM
Nice Article Good working
Pankaj LalwaniPosted Dec 23, 2015, 6:10 AM
doesnt work properly when paging is enabled
Ankit PatelPosted Nov 2, 2015, 3:37 PM
I am using your code but having trouble displaying the grid view in under certain conditions. For example, when there is no customer id present then have no formatting applied except the group total.
Abhay KumarPosted Jul 7, 2015, 1:37 AM
nice one...
David DavidPosted Jun 29, 2014, 2:45 PM
How do I add the header under each 'Customer Name' row
Dinesh GottipatiPosted Mar 20, 2014, 5:22 PM
Thanks for awesome article. Perfectly worked for me
kerry markPosted Mar 11, 2014, 1:44 AM
check this one...http://asp.net-informations.com/gridview/subtotal-grandtotal.htm
Shadi HabbalPosted Dec 9, 2013, 10:17 AM
Great example. Thanks.
Deepika ChaudharyPosted Nov 7, 2013, 7:24 AM
Do you have code for it?
Deepika ChaudharyPosted Nov 7, 2013, 7:24 AM
How can i export the group with subtotal on excel sheet?
omkarachary KPosted Sep 27, 2013, 12:39 AM
Doest it work with Template Fieds as well?
Sharadaprasad SahooPosted Aug 17, 2013, 7:42 AM
i m unable to group the columns when i m passing sql datasource
raj krishnaPosted May 16, 2013, 1:50 AM
thank you so much this code working excellent