【问题标题】:Cell Value Changing Event ,c#单元格值更改事件,c#
【发布时间】:2010-09-29 10:19:05
【问题描述】:

我有一个 DataGridView,其中有 3 列;数量、费率和金额。
DataGridView 是可编辑的。当我在费率列中输入一个值时,该值应立即更改为金额。

Amount=Qty*rate

它正在发生,但是当我单击任何其他单元格时,我希望当我在 Rate 中输入任何值时,它应该乘以 Quantity 并立即反映在 Amount 中而不更改单元格。

【问题讨论】:

  • 你尝试过哪个事件?尝试 DataGridView.CurrentCellDirtyStateChanged 事件

标签: c# winforms datagridview


【解决方案1】:

正如 Sachin Shanbhag 所提到的,您应该同时使用 DataGridView.CurrentCellDirtyStateChangedDataGridView.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;
    }
}

【讨论】:

  • 使用 CommitEdit,CurrentCellDirtyStateChanged 确实按预期工作,每次脏状态发生更改(即用户更改字符串)时都会触发它,感谢 Dmitry!
【解决方案2】:

我没有发现可以正确处理单元格更改值的事件。

您必须将可编辑单元格转换为文本框,然后在其上提供更改的事件。

这是我在浏览某个 MSDN 论坛时发现的代码:

http://social.msdn.microsoft.com/Forums/windows/en-US/a56ac5c1-e71f-4a12-bbfa-ab8fc7b36f1c/datagridview-text-changed?forum=winformsdatacontrols

我也在此处添加代码:

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{

   if (dataGridView1.CurrentCell.ColumnIndex == 0)
   {

      TextBox tb = (TextBox)e.Control;
      tb.TextChanged += new EventHandler(tb_TextChanged);
   }
}

void tb_TextChanged(object sender, EventArgs 
{
   MessageBox.Show("changed");
}

【讨论】:

    【解决方案3】:

    如果您真的想在不更改单元格的情况下更新值(如即时),则必须处理 DataGridView.KeyPress 事件并检查正在更新的单元格。

    如果这太麻烦,请使用DataGridView.CellValueChanged 事件。它比 KeyPress 事件更容易实现。

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      相关资源
      最近更新 更多