DataGridView 列中的计算 [英] Calculation in DataGridView column

查看:34
本文介绍了DataGridView 列中的计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 & 中输入值后总共添加 (A+B)B 列 或离开当前行.并且还想将总列设置为 ReadOnly.

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

这篇关于DataGridView 列中的计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆