• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3823
  • Last Modified:

sum of columns in datagrid view

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
amaimedia
Asked:
amaimedia
1 Solution
 
iboutchkineCommented:
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
 
iboutchkineCommented:
'tour cell'  ---> must be your cell
0
 
Pratima PharandeCommented:
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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
VBRocksCommented:
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
 
VBRocksCommented:
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
 
amaimediaAuthor Commented:
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
 
VBRocksCommented:
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now