gureisu
gureisu

Reputation: 137

How to calculate sum of a column in DataGridView

When I run my WPF and pick a date, it shows the cars rented for that month. In the last column it shows the total price of the rented car. I want to be able to calculate the sum of the values in that total price column. However I'm getting an error that underlines "Cells" in my code.

private void sumButton_Click(object sender, RoutedEventArgs e)
    {

            int sum = 0;
            for (int i = 0; i < TruckDataGrid2.Items.Count; ++i)
            {
                sum += Convert.ToInt32(TruckDataGrid2.Items[i].Cells[2].Value);
            }
            sumText.Text = sum.ToString();



    }

I also want to show the sum in a textbox. Im not sure what I'm doing wrong.

All the packages im using:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PartB.Models;

Upvotes: 0

Views: 1755

Answers (3)

mm8
mm8

Reputation: 169160

You should get the value of the column from the corresponding property of your data object. For example, if you have set or bound the ItemsSource property of your DataGrid to an IEnumerable<Car> and the Car class has a Price property, this should work:

private void sumButton_Click(object sender, RoutedEventArgs e)
{
    int sum = 0;
    for (int i = 0; i < TruckDataGrid2.Items.Count; ++i)
    {
        Car car = TruckDataGrid2.Items[i] as Car; //try to cast item to your data object type
        if (car != null)
            sum += car.Price;
    }
    sumText.Text = sum.ToString();
}

Upvotes: 0

imsanjaysc
imsanjaysc

Reputation: 101

Hope this will work in WPF

for (int i = 0; i < TruckDataGrid2.Items.Count; ++i)      
sum += (decimal.Parse((TruckDataGrid2.Columns[2].GetCellContent(dataGrid.Items[i]) as 
TextBlock).Text));

Upvotes: 2

imsanjaysc
imsanjaysc

Reputation: 101

int sum = 0;
for (int i = 0; i < TruckDataGrid2.Rows.Count; ++i)
{
    sum += Convert.ToInt32(TruckDataGrid2.Rows[i].Cells[2].Value);
}
sumText.text = sum.ToString();

Upvotes: 0

Related Questions