WPF Datagrid 列总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48059789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Datagrid column total sum
提问by
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:
我有一个数据网格,我想总结一列中的所有值。我认为,要做到这一点,我需要逐行对该列中的值求和。但我无法访问行,因为 c# 中的 Datagrid.Rows 代码在 WPF 中不起作用。我访问总项目数:
datagrid.Items.Count;
How can I do datagrid colums total sum in WPF?
如何在 WPF 中执行 datagrid 列的总和?
Datagrid xaml code:
数据网格 xaml 代码:
<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));
}
采纳答案by Racil Hilan
To get the column that you want to sum, use the .Columnscollection 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 TextBlocktype, so cast it, get its Textproperty and parse the value to decimal(or any other type suitable to your values).
要获取要求和的列,请使用.Columns带有列索引的集合属性。然后您可以使用GetCellContent()列上的方法访问其单元格。请记住,单元格的内容是一个TextBlock类型的对象,因此对其进行转换,获取其Text属性并将值解析为decimal(或任何其他适合您的值的类型)。
In your case, you want the eighth column (index = 7), you can try this:
在你的情况下,你想要第八列(索引 = 7),你可以试试这个:
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 - 1because the last item is a placeholder.
请注意,我们循环到Items.Count - 1因为最后一项是占位符。
Alternatively, you can use the ItemsSourceproperty which stores the collection of bound objects, and you then cast each item to the type that you're binding to.
或者,您可以使用ItemsSource存储绑定对象集合的属性,然后将每个项目转换为要绑定到的类型。
You're binding to DataTableand you're calculating the total for the tutarcolumn. You can use the code below to get the total:
您绑定到DataTable并计算该tutar列的总数。您可以使用下面的代码来获得总数:
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 DataTablefrom 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 DataTableinstead of the grid):
但是,由于您是在DataTable从数据库中获取并绑定网格的同一个函数中计算总和,为什么不直接从 中计算总和DataTable?你可以这样做(这与上面的代码非常相似,但直接来自DataTable而不是网格):
decimal sum = 0;
foreach (DataRow row in dbdataset.Rows) {
sum += Convert.ToDecimal(row["tutar"]);
}
Note: Why are you giving your DataTablethe name dbdataset? You should consider naming your variables correctly.
注意:你为什么要给你DataTable的名字dbdataset?您应该考虑正确命名变量。
回答by karthik shankar
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
产品.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.
假设您的 xaml 视图中有一个添加按钮。
Products.xaml.cs
产品.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.
我刚刚在这里添加了更新查询,它将乘以价格和数量并计算总数。

