winforms datagridview 计算字段更改事件 [英] winforms datagridview calculated field change event

查看:15
本文介绍了winforms datagridview 计算字段更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据表绑定的 datagridview.我有一个计算的列 linetotal 乘以单价 * 数量.

I have a datagridview bound from a datatable. I have a calculated column linetotal that multiples unitprice * quantity.

我还有一个总价标签,我想在数据网格视图中包含 linetotal 列的总和.

I also have a totalprice label,that I would like to contain the sum of the linetotal column in the datagridview.

当用户对单价或数量进行任何更改时,该行的 linetotal 应更新,并且 totalprice 标签应与 linetotal 列相加.

When the user makes any changes to unitprice or quantity, the linetotal should update for that line and the totalprice label should sum the linetotal column.

我似乎找不到用于计算总价标签的正确事件.我试过 cellvaluechanged、currentcelldirtystatechanged、rowleave.它们似乎都不能正常工作.我想我需要一个在计算所有 linetotal 列后触发的事件.

I can't seem to find the correct event to use to calculate the totalprice label. I've tried cellvaluechanged, currentcelldirtystatechanged, rowleave. None of them seems to work right. I guess I need an event that fires after all the linetotal columns are calculated.

我的伪代码:

dt = getallitems(itemnumber);
dt.Columns.Add("LineTotal", typeof(double));
dt.Columns["Linetotal"].Expression = "[unitprice] * [quantity]";

dgv.DataSource = dt;

private void dgv_WhatEventToUse???(object sender, DataGridViewCellEventArgs e)
{
    //method to iterate the rows of the datagridview, and sum linetotal column
}

当计算列的值改变时,一定有一些事件会触发.

There must be some event that fires when the value of the calculated column is changed.

推荐答案

看来您的问题来自这样一个事实,即您的计算列是 DataTable 的一部分,而不是 DataGridView 的一部分.我不确定 DataGridView 是否会在 dgv 的基础数据源更改时公开事件.有 DataGridView.DataSourceChanged 事件,但似乎只有在您实际设置 DataSource 属性时才会触发,而不是在 DataTable 随您的计算而改变时触发.

It seems that your problem comes from the fact that your calculated column is part of the DataTable and not part of the DataGridView. I'm not sure if the DataGridView exposes an event for whenever the dgv's underlying data source changes. There is DataGridView.DataSourceChanged event, but that only seems to fire when you actually set the DataSource property, not when the DataTable changes itself with your calculations.

如果您想在不更改代码结构的情况下使其工作,请订阅 DataTable 的 RowChanged 事件,您可以扫描 dgv 并从那里更新您的标签.这并不完全是一个干净的解决方案,但它有效.如果这是一个选项,我会考虑切换到 DataGridView 中的计算列.

If you want to make it work without changing the structure of your code, subscribe to the DataTable's RowChanged event and you can scan the dgv and update your label from there. It's not exactly a clean solution, but it works. I would consider switching to a calculated column in the DataGridView if that's an option.

这篇关于winforms datagridview 计算字段更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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