Solved

sum of columns in datagrid view

Posted on 2007-11-29
7
3,800 Views
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.
0
Comment
Question by:amaimedia
7 Comments
 
LVL 28

Expert Comment

by:iboutchkine
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
        Next
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 20372951
'tour cell'  ---> must be your cell
0
 
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
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 27

Expert Comment

by:VBRocks
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()
        table.Columns.Add("Item")
        table.Columns.Add("Qty")

        '<  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)
        Next

        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)", "")
        MsgBox(sum)


0
 
LVL 27

Expert Comment

by:VBRocks
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)", "")
        MsgBox(sum)

0
 

Author Comment

by:amaimedia
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.
0
 
LVL 27

Accepted Solution

by:
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
form.




0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

785 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