计算的DataGridView列DataGridView

2023-09-03 00:41:48 作者:▽权爷

我有,我想从两个不同的列值总结成第三列一个DataGridView。

I have a DataGridView in which I want to sum up values from two different columns into a third column.

示例DataGridView的:

A   B   Total
1   2    3
25  35   60
5   -5   0

我要添加(A + B)的总量,只是在 A和输入值之后;乙列或离开当前行。而且还需要设置总列如只读

I want to add (A+B) in total, just after entering values in A & B column or leaving current row. And also want to set Total Column as ReadOnly.

推荐答案

您可以做到这一点的CellValidatedEvent,你可以同样的方法适用于RowValidated:

You can do that on CellValidatedEvent and you can apply the same method to RowValidated:

 private void dataGridView_CellValidated(object sender, DataGridViewCellEventArgs e) {
                if (e.RowIndex > -1) {
                    DataGridViewRow row = dataGridView.Rows[e.RowIndex];
                    string valueA = row.Cells[columnA.Index].Value.ToString();
                    string valueB = row.Cells[columnB.Index].Value.ToString();
                    int result;
                    if (Int32.TryParse(valueA, out result)
                        && Int32.TryParse(valueB, out result)) {
                        row.Cells[columnTotal.Index].Value = valueA + valueB;
                    }
                }
            }

您可以设置列只读的设计师,或者是这样的:

You can set column to ReadOnly in the designer, or like this:

dataGridView.Columns["Total"].ReadOnly = true