如何在具有表达式的数据表列的末尾添加总值?

How to add a total value at the end of a datatable column that has an expression?

我想在数据表列的末尾添加一个总值。但我做不到,因为该列有一个表达式。代码如下。请帮忙!

public MainWindow()
        {
            InitializeComponent();

            DataTable table = new DataTable();
            table.Columns.Add("ColA", typeof(double));
            table.Columns.Add("ColB", typeof(double));
            table.Columns.Add("ColSum", typeof(double));

            table.Rows.Add(1.23, 2.34, null);
            table.Rows.Add(2.34, 3.45, null);
            table.Rows.Add(3.45, 4.56, null);

            table.Columns["ColSum"].Expression = "ColA + ColB";
            double total = (double)table.Compute("Sum(ColSum)", "");

            DataRow dr = table.NewRow();
            dr["ColSum"] = total; 
            table.Rows.Add(dr);
            //Can't add total value at the end of ColSum because this column has an expression. How to solve the problem ?

            dataGrid1.ItemsSource = table.DefaultView;
        }

But I can't do it because the column has an expression

没错。这是事实,所以去掉表达式并自己计算总和:

DataTable table = new DataTable();
table.Columns.Add("ColA", typeof(double));
table.Columns.Add("ColB", typeof(double));
table.Columns.Add("ColSum", typeof(double));

table.Rows.Add(1.23, 2.34, 1.23 + 3.45);
table.Rows.Add(2.34, 3.45, 2.34 + 3.45);
table.Rows.Add(3.45, 4.56, 3.45 + 4.56);

double total = (double)table.Compute("Sum(ColSum)", "");

DataRow dr = table.NewRow();
dr["ColSum"] = total;
table.Rows.Add(dr);

如果您选择使用 DataTable 表示您的数据,这是唯一可行的选择。

另一种选择当然是创建您自己的视图模型。