显示数据表的一列值的总和 [英] Show total Sum of values of a Column of a DataTable
问题描述
我想显示商品总价的总和.我面临两个问题:
I want to show sum of total Price of items. I am facing 2 issues:
- 它向我显示了错误的商品总价
- 我想将
.00
添加到总价中
- It's showing me wrong total of items price
- I want to add
.00
to the total price
您可以在图片中查看问题以获得清晰的解释.
You can check issue in the image for a clear explanation.
这是我的代码:
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();
推荐答案
Sum
您可以简单地使用 Compute
数据表的方法并传递表达式进行计算.例如:
Instead of using for loop, You can simply use Compute
method of data table and pass an expression to compute. For example:
var total = yourDataTable.Compute("SUM(Column1)", "");
格式
还要格式化总计以在小数点后显示 2 位数字,您可以使用以下任一选项:
Also to format total to show 2 digits after decimal place, you can use either of these options:
0" 自定义数字格式字符串 :
string.Format("{0:0.00}", total))
固定-点F"格式说明符:string.Format("{0:F2}", total))
更新数据变化的总和
还可以在添加新项目或删除某些项目或更改某些值时在 TextBox
事件中自动显示总和,处理 的
并将结果设置为文本框的ListChanged
事件DataTable.DefaultViewText
.
Also to be able to show the sum automatically in a TextBox
event when new items added or some items removed or some values changed, handle ListChanged
event of DataTable.DefaultView
and set the result as Text
of the text box.
// 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}";
这篇关于显示数据表的一列值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!