how I can show the sum of in a datagridview column

2019-01-06 17:13发布

I need to show the sum of the count column from this datagridview, but I don't know how I can get to the data in the datagridview.

When I click on the button, I want to show 94 in label1.

How can this be done?

alt text

8条回答
干净又极端
2楼-- · 2019-01-06 17:37
 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();
查看更多
Anthone
3楼-- · 2019-01-06 17:50

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();
查看更多
smile是对你的礼貌
4楼-- · 2019-01-06 17:52

you can do it better with two datagridview, you add the same datasource , hide the headers of the second, set the height of the second = to the height of the rows of the first, turn off all resizable atributes of the second, synchronize the scrollbars of both, only horizontal, put the second on the botton of the first etc.

take a look:

   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;
            }
        }
查看更多
叛逆
5楼-- · 2019-01-06 17:54
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();
查看更多
Anthone
6楼-- · 2019-01-06 17:54

Fast and clean way using LINQ

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

verified on VS2013

查看更多
走好不送
7楼-- · 2019-01-06 17:55

If your grid is bound to a DataTable, I believe you can just do:

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

If it isn't bound to a table, you could easily make it so:

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;
查看更多
登录 后发表回答