可能重复:
How to calculate sum of a DataTable's Column in LINQ (to Dataset)?
在我的Data_Grid_View中,我有一个名为Amount的数字列,我想在一个文本框中显示该列的总数,任何人都可以在c#.net
中告诉它的代码是什么答案 0 :(得分:1)
试试这个:
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();
答案 1 :(得分:1)
假设您的金额为double
:
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();
}