Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have dataGrid in wpf, there is a column named 'Sub Total' now I want to calculate the total from subtotal by adding the all rows of sub total column.
like
-- sub total --
10
20
30
on click of Total button I want to display the message that Total is 60.
How to do this in wpf DataGrid c#.

Thanks
Tink

What I have tried:

C#
foreach (DataGridColumn column in grdBill.Columns)
               {
                   ???
               }

I tried something like but not getting how to get this.
Posted
Updated 26-Nov-17 18:53pm
Comments
Graeme_Grant 26-Nov-17 5:51am    
How are you binding the data to the Grid?
Member 11859517 26-Nov-17 6:11am    
I have ProductDetails class, having product properties. from Inpeut textbox i m getting value for properties that I am binding to DataGrid.

<DataGrid Name="grdBill" MinHeight="150" >
<datagrid.columns>
<DataGridTextColumn Header="Bill No." Width="150" Binding="{Binding BillNo}">
<DataGridTextColumn Header="ID" Width="150" Binding="{Binding ProductId}">
<DataGridTextColumn Header="Name" Width="200" Binding="{Binding ProductName}">
<DataGridTextColumn Header="Price" Width="150" Binding="{Binding ProductPrice}">
<DataGridTextColumn Header="Quantity" Width="150" Binding="{Binding ProductQuentity}">
<DataGridTextColumn Header="Sub Total" Width="150" Binding="{Binding ProductSubTotal}">





 private void btnAddBill_Click(object sender, RoutedEventArgs e)
        {
            if (txtQuantity.Text == "")
                return;
            var data = new ProductDetails() 
            { 
                BillNo = 12, 
                ProductId = Convert.ToInt32(txtID.Text), 
                ProductName = txtName.Text,
                ProductPrice = Convert.ToInt32(txtPrice.Text),
                ProductQuentity = Convert.ToInt32(txtQuantity.Text),
                ProductSubTotal = Convert.ToInt32(lblSubTotal.Content)
            };

            grdBill.Items.Add(data);
Graeme_Grant 27-Nov-17 1:17am    
Here is your problem, you are doing WinForm style programming, not WPF. Use an ObservableCollection to hold the data, bind the grid to the ObservableCollection, then you have direct access to the data, no need to hard code against the grid.

Then you can change the grid xaml and bindings or use another control and your code won't break!

1 solution

try this >>
private void calculate()
{
    decimal sum1 = 0;

    foreach (GridViewRow i in this.gv1.Rows)
    {

        decimal e = Convert.ToDecimal(i.Cells[5].Text.ToString());
        sum1 = sum1 + e;
    }

    txtSubTotal.Text = sum1.ToString();

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900