【问题标题】:How to total rows in DGV upon load如何在加载时对 DGV 中的行进行总计
【发布时间】:2011-09-14 16:39:56
【问题描述】:

您好,我正在尝试汇总 DGV 中每一行的单元格,并在加载时将其添加到总列中。我对如何做到这一点有一个想法,但我不确定将代码放在哪里。我知道我可以做类似的事情

        int val1 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[1].Value);
        int val2 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[2].Value);
        int val3 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[3].Value);
        int val4 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[4].Value);

        int val5 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[5].Value);
        int val6 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[6].Value);
        int val7 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[7].Value);
        int val8 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[8].Value);

        dataGridView1.Rows[e.RowIndex].Cells[9].Value = (val1 + val2 + val3 + val4) - (val5 + val6 + val7 + val8);

但问题似乎是我必须使用事件来触发计算。

我们将不胜感激。

韩国

【问题讨论】:

    标签: winforms c#-4.0 datagridview


    【解决方案1】:

    如果您使用数据绑定,您可以在 DataGridView 的 DataBindingComplete 事件中设置行总计。

    您提供的代码看起来会更新总计列,但让我们对其进行一些重构,以便您可以在多个地方使用它:

    private void ComputeAndDisplayRowTotal(int rowIndex) {
        int val1 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[1].Value);
        int val2 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[2].Value);
        int val3 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[3].Value);
        int val4 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[4].Value);
        int val5 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[5].Value);
        int val6 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[6].Value);
        int val7 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[7].Value);
        int val8 = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells[8].Value);
    
        dataGridView1.Rows[e.RowIndex].Cells[9].Value = (val1 + val2 + val3 + val4) - (val5 + val6 + val7 + val8);
    }
    

    在您的 DataBindingComplete 事件中调用此方法,如下所示:

    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) {
        foreach (DataGridViewRow row in dataGridView1.Rows) {
            // Don't want to update the total column on the new row at the bottom of the DGV.
            if (!row.IsNewRow) {
                ComputeAndDisplayRowTotal(row.Index);
            }
        }
    }
    

    现在,如果您允许用户编辑单元格,您可以使用 CellEdnEdit 事件更新行的总计列,如下所示:

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
        ComputeAndDisplayRowTotal(e.RowIndex);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2020-11-25
      • 2021-08-15
      • 1970-01-01
      • 2014-04-27
      • 2014-09-21
      相关资源
      最近更新 更多