单元格值更改事件,c# [英] Cell Value Changing Event ,c#

查看:126
本文介绍了单元格值更改事件,c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGridView,其中有3列;数量,价格和金额。

DataGridView是可编辑的。当我在费率列中输入一个值时,应立即在金额中更改该值。

 金额=数量*费率

正在发生,但是当我点击任何其他单元格时,我希望当我输入任何价值时,它应该与数量相乘,并立即反映在金额,而不改变单元格。 p>

解决方案

正如Sachin Shanbhag所提到的,您应该同时使用 DataGridView.CurrentCellDirtyStateChanged DataGridView.CellValueChanged 事件。在 DataGridView.CurrentCellDirtyStateChanged 中,您应该检查用户是否正在修改正确的单元格(在您的情况下为 Rate ),然后执行 DataGridView.CommitEdit 方法。这里是一些代码。

  private void YourDGV_CurrentCellDirtyStateChanged(object sender,EventArgs e)
{
if YourDGV.CurrentCell.ColumnIndex == rateColumnIndex)
{
YourDGV.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

private void YourDGV_CellValueChanged(object sender,DataGridViewCellEventArgs e)
{
if(e.ColumnIndex == rateColumnIndex)
{
DataGridViewTextBoxCell cellAmount = YourDGV.Rows [e.RowIndex] .Cells [amountColumnIndex];
DataGridViewTextBoxCell cellQty = YourDGV.Rows [e.RowIndex] .Cells [qtyColumnIndex];
DataGridViewTextBoxCell cellRate = YourDGV.Rows [e.RowIndex] .Cells [rateColumnIndex];
cellAmount.Value =(int)cellQty.Value *(int)cellRate.Value;
}
}


I have a DataGridView in which there are 3 columns; Quantity, Rate and Amount.
The DataGridView is Editable. When I enter a value in the Rate Column then immediately the value should be changed in Amount.

Amount=Qty*rate

It is happening, but when I click on any other cell, I want that when I enter any value in Rate it should be multiplied with Quantity and be reflected immediately in Amount without changing the cell.

解决方案

As it was mentioned by Sachin Shanbhag you should use both DataGridView.CurrentCellDirtyStateChanged and DataGridView.CellValueChanged events. In DataGridView.CurrentCellDirtyStateChanged you should check whether the user is modifying the right cell (Rate in your case) and then execute DataGridView.CommitEdit method. Here is some code.

private void YourDGV_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (YourDGV.CurrentCell.ColumnIndex == rateColumnIndex)
    {
        YourDGV.CommitEdit(DataGridViewDataErrorContexts.Commit);                        
    }
}

private void YourDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == rateColumnIndex)
    {
        DataGridViewTextBoxCell cellAmount = YourDGV.Rows[e.RowIndex].Cells[amountColumnIndex];
        DataGridViewTextBoxCell cellQty = YourDGV.Rows[e.RowIndex].Cells[qtyColumnIndex];
        DataGridViewTextBoxCell cellRate = YourDGV.Rows[e.RowIndex].Cells[rateColumnIndex];
        cellAmount.Value = (int)cellQty.Value * (int)cellRate.Value;
    }
}

这篇关于单元格值更改事件,c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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