【问题标题】:Calculate SUM of "Amount" column in DATAGRID's DataGridTemplateColumn on in WPF计算 WPF 中 DATAGRID 的 DataGridTemplateColumn 中“金额”列的总和
【发布时间】:2013-01-27 11:12:33
【问题描述】:

我们有 WPF 应用程序,其中我们在一个表单上使用 DataGrid。 现在我们要在 Window_Loaded 事件中计算该数据网格的“AMOUNT”列的总数,那么它可以在一个 TextBox 中显示 AMOUNT 列的总数吗 当表单被加载时。那么如何遍历 DATAGRID 中的所有行并计算“AMOUNT”列的总数。

如何在 WPF Datagrid 的页脚中显示这个总数?

【问题讨论】:

  • 如何填充DataGrid
  • 我已经通过在其中手动添加行来填充 DataGrid,当我们在 EDIT 模式下打开表单时,那时 DATA 将从数据库中获取。那么现在当我们在 EDIT 模式下打开表单时,DATAGRID 是从数据库中填充的,如何遍历它?

标签: wpf wpf-controls wpfdatagrid wpftoolkit


【解决方案1】:

BindDataGridDataTable。之后,您可以遍历所有行:

        double sum = 0;
        foreach (var row in myTable)
        {
            sum += double.Parse(row["AMOUNT"].ToString());
        }
        myTextBox.Text = sum.ToString()

【讨论】:

  • 好的,我会尝试并让您知道。谢谢你
  • 请您帮忙将我的 DATAGRID 转换为 DATATABLE 吗?
  • 我已将我的 DATAGRID 转换为 DataTable。
  • @ConstantLearner 没问题 :)
【解决方案2】:

将DataGrid转换为DataSet的函数:

namespace WpfApplication1
{
    static class ExtClass
    {
     public static DataSet ToDataSet<T>(this IList<T> list)
     {
         Type elementType = typeof(T);
         DataSet ds = new DataSet();
         DataTable t = new DataTable();
         ds.Tables.Add(t);

         //add a column to table for each public property on T
         foreach (var propInfo in elementType.GetProperties())
         {
             Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

             t.Columns.Add(propInfo.Name, ColType);
         }

         //go through each property on T and add each value to the table
         foreach (T item in list)
         {
             DataRow row = t.NewRow();

             foreach (var propInfo in elementType.GetProperties())
             {
                 row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
             }

             t.Rows.Add(row);
         }

         return ds;
     }

    }
}

编辑:格式化间距以使所有代码显示在代码块中

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 2023-04-07
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多