I have a datagrid and I want to sum up all the values in a column. I think, to do this I need to sum the values in that column row by row. But I cant access rows because Datagrid.Rows code in c# does not work in WPF. I access total items count with:
datagrid.Items.Count;
How can I do datagrid colums total sum in WPF?
Datagrid xaml code:
<DataGrid BorderThickness="0" Name="grid_lab" RowHeight="25" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeColumns="True" CanUserResizeRows="False" AutoGenerateColumns="False" ColumnWidth="*" HorizontalGridLinesBrush="#FFDCDBDB" VerticalGridLinesBrush="#FFDCDBDB" HeadersVisibility="Column" VerticalAlignment="Top" Background="{x:Null}" MouseLeftButtonUp="grid_lab_MouseLeftButtonUp">
Datagrid textcolumn code:
<DataGridTextColumn Binding="{Binding Path=tutar}" Header="Tutar" MaxWidth="50">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Padding" Value="5,0,0,0"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
Total sum code in usercontrol loaded:
decimal sum = 0m;
for (int i = 0; i < grid_lab.Items.Count - 1; i++)
{
sum += (decimal.Parse((grid_lab.Columns[7].GetCellContent(grid_lab.Items[i]) as TextBlock).Text));
}
To get the column that you want to sum, use the
.Columns
collection property with the index of the column. Then you can use theGetCellContent()
method on the column to access its cell. Keep in mind that the content of the cell is an object ofTextBlock
type, so cast it, get itsText
property and parse the value todecimal
(or any other type suitable to your values).In your case, you want the eighth column (index = 7), you can try this:
Notice that we loop to
Items.Count - 1
because the last item is a placeholder.Alternatively, you can use the
ItemsSource
property which stores the collection of bound objects, and you then cast each item to the type that you're binding to.You're binding to
DataTable
and you're calculating the total for thetutar
column. You can use the code below to get the total:However, since you're calculating the sum in the same function which is fetching the
DataTable
from the database and binding the grid, why don't you calculate the sum directly from theDataTable
? You can do it like this (which is very similar to the code above, but directly from theDataTable
instead of the grid):Note: Why are you giving your
DataTable
the namedbdataset
? You should consider naming your variables correctly.Here i did same by using binding. Refer my sample code it may help you. It sums price*quantity and put the total in total column.
Products.xaml
Assume that you are having a add button in your xaml view.
Products.xaml.cs
i just added update query here where it will multiple the price and quantity and calculates the total.