开发者

How to total rows in DGV upon load

Hello I am trying to total the cells of each row in a DGV and add it to a total column upon load. I have an idea on how to do it but I am not sure where to put the code. I know I could do something like

        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 va开发者_运维问答l8 = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[8].Value);

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

But the issue with that it seems is I have to use an event to trigger the calculation.

Any help on this matter would be appreciated.

Kor


If you're using data binding you can set your row totals in the DataGridView's DataBindingComplete event.

The code you provided looks like it will update the totals column but let's refactor it a bit so you can use it in more than one place:

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);
}

Call this method in your DataBindingComplete event like this:

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);
        }
    }
}

Now if you allow the user to edit a cell you can update the row's totals column using the CellEdnEdit event, like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜