我有一个 DataGridView,我想在其中将两个不同列的值相加到第三列中。
示例数据 GridView :
A B Total
1 2 3
25 35 60
5 -5 0
我想在 A & B 列
中输入值或离开当前行后,总共添加 (A+B)。并且还想将 Total Column 设置为 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
关于c# - DataGridView 列中的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097370/