Solved

sum of columns in datagrid view

Posted on 2007-11-29
7
3,788 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
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…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

747 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

13 Experts available now in Live!

Get 1:1 Help Now