【问题标题】:Show total Sum of values of a Column of a DataTable显示数据表一列的总和
【发布时间】:2016-11-19 16:29:22
【问题描述】:

我想显示项目总价格的总和。我面临两个问题:

  • 显示的商品总价有误
  • 我想在总价中加上.00

您可以在image 中查看问题以获得清晰的解释。

这是我的代码:

tDisplay.Text = "Return/" + "Receipt No:" + Return_Form.setalueforText011;
label1.Text = Return_Form.setalueforText011;

OleDbConnection VCON = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Restaurant.accdb");
DataSet dsa = new DataSet();
DataTable dt = new DataTable();
dsa.Tables.Add(dt);

OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("SELECT [Column1],[Column2],[Column3] from [Total] Where [Receipt No] =  " + label1.Text + "", VCON);
da.Fill(dt);
//dataGridView1.DataSource = dt;

for (int i = 0; i < dt.Rows.Count; i++)
{
    products.Add(new tblProduct() { productName = dt.Rows[i]["Column2"].ToString(),productPrice = Convert.ToDecimal(Math.Round(Convert.ToDecimal(dt.Rows[i]["Column1"].ToString())))});
    label3.Text = dt.Rows[i]["Column3"].ToString();
    textBox59.Text = "Rs: "+String.Format("{0:}", Total);
    tblProduct selected = (tblProduct)(listBox60.SelectedItem);
    Total += (decimal)selected.productPrice;
}
VCON.Close();

【问题讨论】:

    标签: c# .net winforms data-binding datatable


    【解决方案1】:

    在您的循环中,您总是将 SelectedItem 行添加到总数中。这始终是第一项,因此您最终会使第一项的价值翻倍。

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        // Create and initialize a new tblProduct from the datatable row
        tblProduct current = new tblProduct();
        current.ProductName = dt.Rows[i]["Column2"].ToString();
        current.productPrice = Convert.ToDecimal(Math.Round(Convert.ToDecimal(dt.Rows[i]["Column1"].ToString())));
    
        // Add to your list of products
        products.Add(current);
    
        // This line is wrong because you overwrite the value at each loop
        label3.Text = dt.Rows[i]["Column3"].ToString();
    
        // Sum the price of the current tblProduct
        Total += (decimal)current.productPrice;
    }
    // Outside the loop update your total label
    textBox59.Text = "Rs: "+String.Format("{0:0.00}", Total);
    

    如果您允许我提供建议。不要以这种方式命名您的控件。它们不可读且不易识别。从现在开始看这段代码,你会很难记住哪个控件是 textBox59 或 listBox60。

    【讨论】:

    • 非常感谢先生,我真的很感谢你,你真的是在杀死天才,如果你不介意列表框,我可以再问你一个问题
    • 在我的第一个问题中我还要问你一件事,我如何在商品价格中添加 .00
    • 这部分问题我不清楚。我看不到您如何将项目添加到 ListBox。但是,如果您从产品列表中获取项目,那么您需要像现在一样格式化它们。
    • @michaeljohn 将 Total 变量设为双精度并调用 Total.ToString("0.00")。
    • 再次感谢您的回复。我不是在我的主表单中询问这个列表框,我正在使用另一个列表框,我想要当我点击按钮时,所以所有项目的前景色都变成红色,之后如果我在列表框中添加另一个项目,所以这个项目的前景色是黑色的,而不是红色的
    【解决方案2】:

    总和

    您可以简单地使用数据表的Compute方法并传递一个表达式来计算,而不是使用for循环。例如:

    var total = yourDataTable.Compute("SUM(Column1)", "");
    

    格式

    还可以将总计格式化为显示小数点后 2 位,您可以使用以下任一选项:

    根据数据变化更新 Sum

    还能够在添加新项目或删除某些项目或更改某些值时在TextBox 事件中自动显示总和,处理DataTable.DefaultView 的ListChanged 事件并将结果设置为Text 的文本框。

    示例

    // Define data table
    var dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Price", typeof(int));
    
    // Fill data
    dt.Rows.Add("Product 1", 100);
    dt.Rows.Add("Product 2", 200);
    
    // Set data source of data grid view
    this.dataGridView1.DataSource = dt;
    
    // Automatically update text box, by SUM of price
    textBox1.Text = $"{dt.Compute("SUM(Price)", ""):F2}";
    dt.DefaultView.ListChanged += (obj, args) =>
        textBox1.Text = $"{dt.Compute("SUM(Price)", ""):F2}";
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      相关资源
      最近更新 更多