Home » VB.Net

Gridview Subtotals and totals

my table has div code, inventory date, landfill name , no of tonnes and total tonnes for a particular division and month tht the user selects

i need to display data such as show below as a sample:-

Division Month   day Landfill Name No Of Loads Total tonnes
000        August  1     Niagara            10                   5
000        August  2     Niagara            10                   5
000        August  3     Niagara            10                   5
000        August  4     Niagara            10                   5
000        August  5     Niagara            10                   5
000        August  6     Niagara            10                   5
000        August  7     Niagara            10                   5
Week Total                                         70                  35
000        August   8     Niagara            10                   5
000        August   9     Niagara            10                   5
000        August  10     Niagara            10                   5
000        August  11     Niagara            10                   5
000        August  12    Niagara            10                   5
000        August  13     Niagara            10                   5
000        August  14     Niagara            10                   5
Week Total                                         70                  35

 and so on for weekly also a grand total for all weeks after the last week of the current landfill

and then for the next landfill do the same weekly totals

and then grand totals

Can anyone help me how






5 Answers Found


Answer 1

for that you need to create DataTable and add row one by one with the data  into DataTable and assign to Grid.

Based on you requirement you must be made logic for this.


Answer 2

Thanks MItesh

I do appreciate you helping me

I solved the above requirement with a Gridview..................... 




Answer 3

You probably have the data  at RowDataBound or RowCreated event.  Add each number to two totals  (one for weekly, one for grand).

When gridview  displays, put these totals in labels - done.


Answer 4

You can do it with LINQ like this

var records = new[] { new { month  = "August",day = "1", Tonnes = 5 } }.ToList();
//Test Records for a month
for (int i = 2; i < 31; i++)
    records.Add(new { Month = "August", day  = i.ToString(), Tonnes = 5 });
//Select week dates and calculate running total
// Add grandTotal after every week
records.Where(a => new string[] { "7", "14", "21", "28" }.Contains(a.day)).ToList().
                    ForEach(x => records.Insert(records.IndexOf(x) + 1, new
                        Month = "Week Total",
                        day = "",
                        Tonnes = records.Where(z => z.day != "").
                                            Where(a => Convert.ToInt32(a.day) >= Convert.ToInt32(x.day) - 6 &&
                                                    Convert.ToInt32(a.day) <= Convert.ToInt32(x.day))
                                        .Sum(b => b.Tonnes)
GridView2.DataSource = records;
//Highlight GrandTotal Rows
GridView2.Rows.Cast<GridViewRow>().Where(a => a.Cells[0].Text == "Week Total").
                ForEach(a => a.BackColor = Color.FromName("#E2DED6"));

Answer 5

Perhaps you don't image that codes will be so easy, just call this:
protected void Page_Load(object sender, EventArgs e)
    GridViewHelper helper = new GridViewHelper(this.GridView1);
    helper.RegisterGroup("ShipRegion", true, true);
    helper.RegisterGroup("ShipName", true, true);

do you want to know how it functions?
Please download the sample  here:


Hi all,

I'm creating a crystal report in Visual Studio 2005 Pro edition.
I want to add a Sub Total and Grand Total for all my records on the report.
Total I have 2 pages in this report. I directly connect to SQL Express 2005 table.

Now I have added 2 Summary fields but they sum all the value.
What I want is "summary value/Sub Total" for each page. 
And at last page, I want a Grand total.
So, I use this summary as my Grand Total and I put it inside "Report Footer" section. So, its solved.

I don't have any column to group.
But can anyone guide me on SubTotal??? How to do it??



Hi! I have a report I am working on. In it there are a few values.

1. Budget = clppBudget

2. Adjustments = [subreport_CLPEscalatedAdjustments].[Report]![CCPAdjustmentTotal]

3. Subtotal (Budget + Adjustments) named CCPIDBudgetTotal = [clppBudget]+[subreport_CLPEscalatedAdjustments].[Report]![CCPAdjustmentTotal]

This report shows those three values for several different construction projects. I would like to have a grand total in the report footer that sums all of the subtotals, but am not sure how to proceed. I tried using =Sum([CCPIDBudgetTotal]) but that is not working. Please let me know if you need any additional information.

Thanks! Stacey


I have implemented column tolals in the footer of my gridview using the technicque described in this article http://aspalliance.com/782 .

Now I would like to have a total of the 7 column totals that are displayed in the footer.  Can anyone tell me how to do this.  I would like to display this in a label or an addition row in the footer if that is possible.



I have a gridview where I am doing editing. Gridview Data is like this.

Country        Fruit            Quantity

Canada       Mango             5

                   Apple             10

                  Orange         20

                  Total            35

Brazil          Mango          0

                 Apple          20

                 Orange         5

                 Total           25


If amy user change the value, While editing , Total amount should get change. How can we do this. I have added OnTextChanged event for the txtQunatity. How can I get all the value and I can calculate total?








Is there a solution to show total items in Grid View in List.aspx or GridViewPager

Eg. Record: 1 - 20 of 231 


 I am having problems with displaying the totals in the footer of a gridview. I am writing a page whereby users can enter comments and marks for an online photo competition.

The page has a details view to enter the comment and mark. Its has a details view where the photo is displayed. It has a gridview where the comments and marks that have been entered are displayed.

It works well - the details view allows comment and mark entry and the gridview show the comments and marks as they are entered. The problems are twofold. Firstly the total shows double the marks that should be displayed. Secondly, when you leave the page and then return later, you have to refresh the page before it will show the latest comment and mark even though it shows this immediately after entering the data.

Ive provided my code below:


Partial Class PhotoAlbum_PhotoDetails

    Inherits System.Web.UI.Page

    Private TotalMarks As Decimal

    Protected Sub DisplayComment_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles DisplayComment.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            TotalMarks += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Mark"))

        ElseIf e.Row.RowType = DataControlRowType.Footer Then

            e.Row.Cells(3).Text = TotalMarks

        End If

    End Sub


    Protected Sub CommentInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles CommentInsert.ItemInserting

        e.Values("UserID") = Membership.GetUser().ProviderUserKey

        e.Values("PictureID") = Request.QueryString("ID")

        e.Values("CommentMadeOn") = DateTime.Now

        e.Values("Subject") = Membership.GetUser.UserName

    End Sub

End Class


Hi all,

           I will have a gridview with checkboxes and some amount fields. I would like to display the sum of the amount in gridview footer depending on the checked items by the user. Can any one give me a sample code


i have a gridview in which i have added two textboxes .

the second textbox is placed in footer of gridview

wht i want is when the user enters values in the first textbox the total of these textboxes should be displayed in footer row.

Pls help



I have a form where i have three textboxes  and a gridview with two template textboxes.Now i need to get the total of all the textboxes  including the template textboxes in another textbox named Total.I know how to get the total of textboxes using javascript.But now what i need is to get the total of all textboxes including the template textboxes in the Total textbox and also the value of total textbox should change if i change the previously entered value of any textbox 

ie,if T1,T2,T3 are the textboxes and GridTxt1,Gridtxt2 are the Template textboxes then

Total=T1+T2+T3+GridTxt1+GridTxt2 and also

if T1=1: T2=1:T3=1:gridTxt1=1: GridtXt2=1

Total=5 but if i change the value of T1 to 2 and Gridtxt2 to 4

Total should be=7


pls help

Thanks in advance



I have been asking this for a long time.But the answer what i get is not want i need.I have a  gridview with two template text box (t1 and t2) inside gridview and four textboxes outside the gridview on the form (txt1,txt2,txt3,txt4).All these textboxes allow only integer value to be entered.What i need is to get the total of all these textboxes (ie,template textboxes as well as textboxes outside gridview) in a textbox named Total at the same time we enter values in a textbox.Also if i change the value of a textbox later that too should be reflected in the Total textbox .I know how to calculate the total of the textboxes outside the gridview.But i need the total of all textboxes including template as well as textboxes outside simultaneously

Pls help and thanks in advance


Wow, so i know this really shouldnt be this hard to do, but im having the hardest time finding information on this that makes any sense. i am using linq to get data from my SQL server 2005 database and bind it to a gridview. From the table i am pulling two fields...Reference(the item name) and Cost. In the gridview i have added two additional columns, Quantity and total. I need to allow the user to change the quantity field to the amount they need to order and update the total field for that row. Also i would like to show a grand total at the bottom of the gridview summing all the total fields. The totals need to be updated as soon as the the user clicks or tabs out of quantities field. Here is the code for my gridview.




























































gvOrdersheet.DataSource =




protectedvoid Page_Load(object sender, EventArgs e)MembershipUser user = Membership.GetUser();string currentUser = user.ProviderUserKey.ToString();GYTDataContext gyt = newGYTDataContext();from i in gyt.UserItemsjoin u in gyt.Items on i.ItemId equals u.ItemIdwhere i.UserId.ToString() == currentUserselectnew


Reference = u.Reference,

Price = u.Price





Please help



Hey :)

I would like to know if someone can please help me

How can I loop through and find the TOTALS of all labels with the same values


For Each gvrow As GridViewRow In InsertedCompanies.Rows

Dim lblRegistrationComplete As Label = DirectCast(gvrow.FindControl("lblRegistrationComplete"), Label)

Dim lblIsJobPayedFor As Label = DirectCast(gvrow.FindControl("lblIsJobPayedFor"), Label)

Dim lblOutstanding As Label = DirectCast(gvrow.FindControl("lblOutstanding"), Label)

Dim lblJobPayedPrice As Label = DirectCast(gvrow.FindControl("lblJobPayedPrice"), Label)


If lblRegistrationComplete.Text = "True" And lblIsJobPayedFor.Text = "False"  Then

                lblOutstanding.Text = "Outstanding"
                lblOutstanding.Text = "Not Outstanding"

            End If



How do I get the total of how many "Outstanding" there is  and how many Not Outstanding

I seriously appreciate your time, help and advise on this

Thank you so much



Hi all,

I have a view where i group the projects and their hours per week. I can get totals for the hours for the groups per week and based on that we do a calculation to see if we are overtime or under. Is there a was to sum all the totals from each group? I need to group by week first to caculate the week overtime and then see the total overtime. Any ideas?

  Week     Hours Worked         Overtime (based on 37.5)


   24               39                             +1,5

   25               37                              -0,5 


                               Total Overtime: +1



How can I get the sum of Total in my Y-Axis so that the results are grouped?

Chart3.Series("Series1").YValueMembers = "Total" ' i want the sum of total of the X-Axis value

Is this possible or do I have to run that in my sql query?



I have a an issue in caliculating the rowgroup totals. There are 3 student who are appreaed for the exams for different subjects. i have displayed teh same in matrix table like below


  Exam Group1The current Overal Pass Status isOveral Pass Status Should be
Java (Marks)Pass StatusSQL
Pass Status  
slnoStudent Name      
1           A20       1        10       0         00
2            B10        0        20       1        00
    3            C30        1       30       1        11
Total Passed 2        2        41
Total Failed 1       1        22




 The problem is at totals last column i.e The total overal passed students should be 1 instead it is  showing as 4 (2+2). The Tablix is doing the total caliculations like, the column group total is done on the row group totals instead of the same colun group values. Please help me out.


Total Passed 2 2         4 1
Total Failed 1 1         2 2


Thanks in advance,




I'm trying to call the Subtotals function (of the Range object) several times (to get nested sub-totals), but the problem is that I also get a grand total for every field I do the sub-total for, instead of getting a grand total only for the outermost field, like I get when doing that directly in Excel. Has anybody ever had this problem and / or knows how to solve it?



Hi All,

I have RDLC report. My Detail report is bringing the data group by the criteria selected. For example I select the criteria Age. so all data with age 11 comes up, then all data with age 12 comes up.Till here I am able to do with stored proc but now what I want is, Say there are 4 rows with age 11,  I want total at the bottom of row to show 4. Then say there are 6 rows with age 12 , At the bottom of 12 age show Total 6. Then Grand total = 10 (4+6 ). How do I achieve this. Any Idea..I want something like (This one sorted by Contact Relationship)

Child's NameAgeContact NameContact Relationship   AgencyDate Received
Phil Drummond16Paul BerrymanFamily MemberDCF5/22/2008
Lawrence Higgins1Fredrick PleasantFamily MemberDPH7/12/2008
Paul Cote9Kittie HawkinsFamily MemberDCF7/14/2008
Devlin Harris11Cheri GlasserFamily MemberDYS9/19/2008
Total: 4
Robert Sherman12Ron SmithSocial WorkerDYS5/3/2008
Brian Montgomery5Deice DrumgoldSocial WorkerDYS6/30/2008
Peter Zimmerman16Dale EversonSocial WorkerDCF8/21/2008
Sean Johnson17Glen MondaleSocial WorkerDTA9/17/2008
Total: 4
Roger Donoghue17Jesse VentureUnknownDYS6/30/2008
Kevin Draper14Gary ForesterUnknownDYS8/27/2008
Total: 2
Grand Total: 10


Hi, Please help

I am using RS2008
I have a Tablix with a row grouping by Location and a row field Totalling the current employee count for that state

I have three adjacent columns grouping by Month, based on what month is selected in the multivalue-parameter, one column returns back number of employees joined for those months. second column how many left for those month. The third column the total headcount for those months

FOR Example if the parameter selected was Jan, Feb, March, the below would be returned

                                 JOIN                   LEFT                  HEADCOUNT
     CURRENT      Jan  Feb March         Jan Feb March         Jan Feb March 
WA     15              2    3    4                 3    1     2            14   16    18
VIC    23              1    4    5                 3    4     1             21   21    28

In the headcount I would like the total headcount to be a running value
ie for the WA Jan Headcount column it should be Current + Join - Left = 15 + 2 - 3 = 14

In february I would like to use the Value which was calculated in the month of January
i.e 14 + Join - Left = 14 + 3 - 1 = 16

In March it would use the Value which was calculated in the month of Feb
16 + join - Left = 16 + 4 - 2 = 18

The value I have under the Column month grouping is

Sum(field.currentemployee.value,"Location") + sum(field.join.value) - sum(field.left.value)

This is the correct number for the Jan column headcount but for Feb and MARCH The starting value is incorrect. Because the Months are dynamic Im not sure how to do this

The output above is what I would like to achieve...can anyone please help on this problem, can this be done at all ?

thanks in advance


I am having a matrix report  in ssrs 2005 with parameters.It is having 3 rows grouping  and one column grouping .I am subtotal on the 3th row group and I need to pass the parameters from the subtotal to drill through report.When I am trying to pass the parameters using inscope function it is not getting passed to the drill through report.


I am pasting the copy of the matrix report.


     Country                          Plan                                                                                                                                                              LocationsSubmissionMissing ApprovalsRejected
           USA                  NDBIA - Moines121
IL - Chicago100
IN - Wayne100
IN - Indianapolis100
MI - Grand 100
MO - Kansas 100
MO - St Joseph000
MO - St Louis010
OH - Cleveland000
TX - Dallas100
(NDB) Total         73


                          Country(total)                                                                                                             7            3            1

When I click on the '7' I  need to see the 7 Record related to them But I am seeing only the first record  related to IA - Moines .

I am trying to pass the parameters in the following form

I clicked on the subtotal --->properties--->navigation--->parameters

parametersname  Parameter value

Country   =Fields!Country.Value

Plan=                 Fields!PLAN.Value

Locations= Fields!Location.Value

Locations is a multivalued in the sub report. When  I am trying to pass a default value for the Locations in  sub report it is giving error

I tried to pass as follows

( Location IN(@Location) OR @Location='-1') but when i make it a single valued ( and in main report in the subtotal navagation---->Parametersname  Parameter value

Location= IIF(INSCOPE("Locationgroup") , Fields!Location.Value,"-1")  it not giving error but  when i click on the sub total in the main report  location dropdown list is empty


I need to pass the parameter from the Country Total also.

So can any one help me out


Thanks in Advance 



I've found the following thread: http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/5ee3c115-a02b-4295-91a4-e8df8b7f01c9?prof=required and following up the linked threads in this first thread, but I've got a similar issue about calculating the percentages and can't find the errors in my thoughts.

My system: I'm using SSRS 2005 Service Pack 2(Prod) and Service Pack 3 (Test) and experiencing the issue below on both systems.

I've got a matrix with 4 row groups and a Static Group with 3 Columns, so it looks like this:

                                           Data                     Data2                 Data3                  
<RowGroup1>      <RowGroup2>     <RowGroup3> <RowGroup4>  detailColumn1  detailColumn2    detailColumn3    

Data: =Sum(Fields!data1.Value)

Data2: =Sum(Fields!data2.Value)

Data3 should contain the difference between Data and Data2 in proportion to the Total of Group3 for the Data-column. And I thought the following expression would do the trick:

=Abs(Sum(Fields!data1.Value)-Sum(Fields!data2.Value)) / Sum(Fields!data1.Value, "<RowGroup3Name>")

That didn't do it, so I simplified the formula for debugging reasons to give me:

Data3: =Sum(Fields!data1.Value, "<RowGroup3Name>")

I expected the result that the value displayed in the subtotal for RowGroup3 is now displayed in every data cell belonging to this group. But instead all datacells are showing me the sum for RowGroup1, so I get the following matrix (filled with example data).

                                                                                      Work    Reported Work    Data3
[Year 2010]   [Month Jan]   [Project A]   [Department B]     10              5                    24
                                                          [Department C]      5               5                    24
                                        Total                                       15             10                  24
                                        [Project B]    [Department B]     2               1                    24
                                        Total                                        2               1                   24
                    [Month Feb]   [Project A]    [Department B]     5              10                   24
                                        Total                                        5              10                   24
                                       [Project B]    [Department B]      2               1                    24
                                       Total                                         2               1                    24

So, why is he using the Year (RowGroup1) in the Sum-Function as Scope and not the RowGroup3 I have told him to use?
I tried the InScope()-Function and if I set Data3=IIF(InScope("RowGroup3Name"), "true", "false") it gives me false for all cells. So why is this cell not in scope of RowGroup3 but in scope of RowGroup1?

I would really appreciate your help on where I'm going wrong!


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure