【发布时间】:2011-08-04 11:11:06
【问题描述】:
可能重复:
How to calculate sum of a DataTable's Column in LINQ (to Dataset)?
在我的 Data_Grid_View 中,我有一个名为 Amount 的数字列,我想在一个文本框中显示该列的总计,谁能告诉它在 c# .net 中的代码是什么
【问题讨论】:
标签: c#
可能重复:
How to calculate sum of a DataTable's Column in LINQ (to Dataset)?
在我的 Data_Grid_View 中,我有一个名为 Amount 的数字列,我想在一个文本框中显示该列的总计,谁能告诉它在 c# .net 中的代码是什么
【问题讨论】:
标签: c#
假设您的金额为double,以下是使用 LINQ 的方法:
dataGridView.Rows.OfType<DataGridViewRow>()
.Sum(row => Convert.ToDouble(row.Cells["Amount"].Value));
以下是它实际适合您的程序的方式:
private void button2_Click(object sender, EventArgs e)
{
decimal sum = dataGridView1.Rows.OfType<DataGridViewRow>()
.Sum(row => Convert.ToDecimal(row.Cells["Money"].Value));
textBox1.Text = sum.ToString();
}
【讨论】:
OfType<DataGridViewRow>() ,因为Rows 实现了IEnumerable 而不是IEnumerable<T>(LINQ 需要)。
sum。请参阅我的编辑以了解如何正确执行。
试试这个:
int sum = 0;
int ColumnIndex=1; //your column index
//Iterate through all the cells of Specified ColumnIndex in each row and get the sum
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += int.Parse(dataGridView1.Rows[i].Cells[ColumnIndex].Value.ToString());
}
//display sum
textBox1.Text = sum.ToString();
【讨论】:
textBox1.Text = sum.ToString()!