我有一个DataGridView,我想将两个不同列中的值求和成第三列。
示例DataGridView:
A B Total
1 2 3
25 35 60
5 -5 0
我想在
A & B column
中输入值或离开当前行后总计加(A + B)。并且还希望将“总计列”设置为ReadOnly
。 最佳答案
您可以在CellValidatedEvent上执行此操作,并且可以将相同的方法应用于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;
}
}
}
您可以在设计器中将列设置为ReadOnly,或这样:
dataGridView.Columns["Total"].ReadOnly = true