sum of columns in datagrid view

Posted on 2007-11-29
Last Modified: 2013-11-26
Hi experts
 I have a datagrid view which i fill from datatable. How could I sum the columns in datagrid view?

display in datagrid view
VrstaAvta      11/02/2007      12/03/2007 ...
JednoVratni      2            4
DvoVratni         2             4
TroVratni          2             5

and I need:

VrstaAvta      11/02/2007      12/03/2007 ...
JednoVratni    2                       4
DvoVratni       2                       4
TroVratni        2                       5
Sum               6                        13

I know that I can do this sum operation in datatable which is my source for this datagrid view, but I try to avoid this method.
Question by:amaimedia
LVL 28

Expert Comment

ID: 20372947
in dgv

        For i As Integer = 0 To dgv.RowCount - 1
            lblSum.Text += dgv.Rows(i).Cells(4).Value ' here use tour cell ordinal position
LVL 28

Expert Comment

ID: 20372951
'tour cell'  ---> must be your cell
LVL 39

Expert Comment

by:Pratima Pharande
ID: 20373039
You can try with adding lable control in Template cloumn  & then in Itemdatabound event just fetch the values form first to cells and do the operations ,and dispay that value in txt property of the lablel

For this you need to find the perticular lable in that row and then set text property
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

LVL 27

Expert Comment

ID: 20374174
Why avoid using the DataTable?  It's very easy!

Here's an example of how easy it is to retrieve your sum (totalling the "Qty" column):
    Dim sum As Int32 = table.Compute("Sum(Qty)", "")

Here's a more complete example:
        'Create a table and set it as the DataSource for the DataGridView
        Dim table As New DataTable()

        '<  Set the datatype for columns that will be calculated
        table.Columns("Qty").DataType = GetType(System.Int16)

        'Loop and add rows to table
        For i As Int16 = 1 To 5
            table.Rows.Add("Item " & i.ToString, i)

        Me.DataGridView1.DataSource = table

        '*** Here's the really easy part:

        'Get a reference to the table that is the datasource
        Dim dt As DataTable = Me.DataGridView1.DataSource

        'Get the Sum of the "Qty" column
        Dim sum As Int32 = table.Compute("Sum(Qty)", "")

LVL 27

Expert Comment

ID: 20374185
Oops, I forgot to set the retrieved table for the Compute, so it should be:

        '*** Here's the really easy part:

        'Get a reference to the table that is the datasource
        Dim dt As DataTable = Me.DataGridView1.DataSource

        'Get the Sum of the "Qty" column
        Dim sum As Int32 = dt.Compute("Sum(Qty)", "")


Author Comment

ID: 20380696
I know  the Compute method, but I  would prefer to do this sum operation direct in the  datagrid view if it s possible. I don t want to change datatable because i need it for other operations,and I don't need this row(Sum) in datatable I only need it for display in datagrid view.
LVL 27

Accepted Solution

VBRocks earned 500 total points
ID: 20382779
Well, wait a second...  The compute method does not change the DataTable in any way (does not add any columns or rows).  All you do is tell it which column to calculate, and what type of calculation to
perform.  It returns the calculated value.

You will not be able to perform/display any type of calculations in the DataGridView, if it is bound
to a DataTable or DataView (if you set the DataSource to a DataTable or DataView).

If you DataGridView is not bound to a DataTable or DataView, and you are adding the rows manually,
then you can loop through all of the rows in the DataGridView and calculate the values from the
desired column, and then add a row to the end of the grid to display the results.  However, if the user
decides to sort the grid after the row has been added, then it will get sorted with the rest of the rows,
and that would be very undesirable.  If you decide to take that route, then I would suggest disabling
column sorting.

But let me tell you what I think would be a better approach for you:
    Add a new UserControl to your project, and name it something like "Grid"
    From the ToolBox, add a StatusStrip to the user control, leave it docked to the bottom.
    Add labels (at least 1) to the StatusStrip to display calculated results (name it "lblCalcResults1")
        Delete the text from each of the labels you add to the StatusStrip
    Add a DataGridView to the user control, and set the Dock to fill (leave the name as DataGridView1)
    Save and Build your project.
    Go to your form where your DataGridView is, and delete the DataGridView.
    Go to the ToolBox, and look at the very top for the "Grid" user control,
        then drag and drop it on the form.
    Load your data into your DataTable, and then set the DataSource for the DataGridView like you
        normally would:

            Me.Grid1.DataGridView1.DataSource = myDataTable

    Next, Using the Compute method, calculate the total of a column and display it's results at the
        bottom of the DataGridView, in the StatusStrip label, example:

            'Get the Sum of the "Qty" column
            me.Grid1.lblCalcResults1.Text = "Sum of Qty:  " & _
                   myDataTable.Compute("Sum(Qty)", "").ToString()

So together, you code would look like:
            Me.Grid1.DataGridView1.DataSource = myDataTable
            Me.Grid1.lblCalcResults1.Text = "Sum of Qty:  " & _
                myDataTable.Compute("Sum(Qty)", "").ToString()

And that's it.  Another option is (not) creating a UserControl, but just adding the StatusStrip to the bottom
of your form (which is what I normally do), and add your DataGridView directly on to your form.  Then,
use the Compute method to return the calculated results to the StatusStrip label at the bottom of your


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
WPF - Tooltips for ComboBox items 5 40
Help with Syntax 9 29
Where can I ask about my ASP.NET MVC project? 6 23
VB.NET Repostiory Pattern 7 17
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now