我如何在datagridview列中显示总和?

我需要显示此datagridview count列的总和,但我不知道如何获取datagridview中的数据。

当我点击按钮时,我想在label1显示94

如何才能做到这一点?

替代文字

 int sum = 0; for (int i = 0; i < dataGridView1.Rows.Count; ++i) { sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value); } label1.text = sum.ToString(); 

如果您的网格绑定到DataTable ,我相信您可以这样做:

 // Should probably add a DBNull check for safety; but you get the idea. long sum = (long)table.Compute("Sum(count)", "True"); 

如果它没有绑定到表,你可以很容易地这样做:

 var table = new DataTable(); table.Columns.Add("type", typeof(string)); table.Columns.Add("count", typeof(int)); // This will automatically create the DataGridView's columns. dataGridView.DataSource = table; 

使用LINQ快速而干净的方式

 int total = dataGridView1.Rows.Cast() .Sum(t => Convert.ToInt32(t.Cells[1].Value)); 

在VS2013上validation

如果可以,请使用LINQ。

  label1.Text = dataGridView1.Rows.Cast() .AsEnumerable() .Sum(x => int.Parse(x.Cells[1].Value.ToString())) .ToString(); 
  decimal Total = 0; for (int i = 0; i < dataGridView1.Rows.Count; i++) { Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value); } labelName.Text = Total.ToString(); 

将总行添加到将绑定到网格的数据集合中。

你可以用两个datagridview做得更好,你添加相同的数据源,隐藏第二个的头部,设置第二个的高度=第一个行的高度,关闭第二个的所有可resize的属性,同步两个滚动条,只有水平,第二个滚动条放在第一个等的底部。

看一看:

  dgv3.ColumnHeadersVisible = false; dgv3.Height = dgv1.Rows[0].Height; dgv3.Location = new Point(Xdgvx, this.dgv1.Height - dgv3.Height - SystemInformation.HorizontalScrollBarHeight); dgv3.Width = dgv1.Width; private void dgv1_Scroll(object sender, ScrollEventArgs e) { if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll) { dgv3.HorizontalScrollingOffset = e.NewValue; } } 
 //declare the total variable int total = 0; //loop through the datagrid and sum the column for(int i=0;i