how I can show the sum of in a datagridview column?

后端 未结 8 1432
日久生厌
日久生厌 2020-11-27 05:46

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

相关标签:
8条回答
  • 2020-11-27 06:18

    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;
    
    0 讨论(0)
  • 2020-11-27 06:24

    Use LINQ if you can.

      label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                       .AsEnumerable()
                                       .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                       .ToString();
    
    0 讨论(0)
  • 2020-11-27 06:29
     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();
    
    0 讨论(0)
  • 2020-11-27 06:31

    Fast and clean way using LINQ

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

    verified on VS2013

    0 讨论(0)
  • 2020-11-27 06:36

    Add the total row to your data collection that will be bound to the grid.

    0 讨论(0)
  • 2020-11-27 06:37
    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();
    
    0 讨论(0)
提交回复
热议问题