1
votes

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));
        }
3
@Why dont use a model and bind total to a column, instead of calculating from the grid.Eldho

3 Answers

1
votes

To get the column that you want to sum, use the .Columns collection property with the index of the column. Then you can use the GetCellContent() method on the column to access its cell. Keep in mind that the content of the cell is an object of TextBlock type, so cast it, get its Text property and parse the value to decimal (or any other type suitable to your values).

In your case, you want the eighth column (index = 7), you can try this:

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));
}

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 the tutar column. You can use the code below to get the total:

decimal sum = 0m;
foreach (DataRowView row in grid_lab.ItemsSource) {
    sum += (decimal)row["tutar"];
}

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 the DataTable? You can do it like this (which is very similar to the code above, but directly from the DataTable instead of the grid):

decimal sum = 0;
foreach (DataRow row in dbdataset.Rows) {
    sum += Convert.ToDecimal(row["tutar"]);
}

Note: Why are you giving your DataTable the name dbdataset? You should consider naming your variables correctly.

0
votes

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

  <DataGrid AutoGenerateColumns="False" Height="150" HorizontalAlignment="Left" Margin="108,169,0,0" x:Name="dataGrid1" VerticalAlignment="Top" Width="365" ItemsSource="{Binding}" DataGridCell.Selected="dataGrid1_Selected">
          <DataGrid.Columns>   
           <DataGridTextColumn Header="Product Price" Binding="{Binding productprice}"/>
           <DataGridTextColumn Header="Product QTY" Binding="{Binding productqty}" />
           <DataGridTextColumn Header="Total" Binding="{Binding total}" x:Name="total" />
          </DataGrid.Columns> 
    </DataGrid>

Assume that you are having a add button in your xaml view.

Products.xaml.cs

private void addButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NpgsqlConnection con = new NpgsqlConnection("Server=00.0.0.00;Port=1111;Database=TEST_DB;User Id=postgres;Password=****;");
                con.Open();
                NpgsqlCommand cmd = new NpgsqlCommand("insert into Product(productprice,productqty)values('"+ prodprice.Text.ToString() + "','" + prodqty.Text.ToString() + "')", con);
                NpgsqlCommand cmd2 = new NpgsqlCommand("update Product set total=productprice*productqty", con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                cmd2.ExecuteNonQuery();
                con.Close();
                errorMessage.Text = "Item Added Successfully";
                prodprice.Text = prodqty.Text = "";
                NpgsqlCommand cmd1 = new NpgsqlCommand("select *from Product", con);
                NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(cmd1);
                DataTable dt = new DataTable("Product");
                adapter.Fill(dt);
                dataGrid1.ItemsSource = dt.DefaultView;
            }
            catch (NpgsqlException)
            {
                errorMessage.Text ="Enter Valid Data" ;
            }
        }

i just added update query here where it will multiple the price and quantity and calculates the total.

0
votes
int sum = 0;
for (int i = 0; i < datagrid1.Items.Count; i++)
{
      dynamic s = datagrid1.Items[i]; // select row i in datagrid
      sum += s.NamteOfTheColumnInDataBase; // access to special field(column) of row
}