DataGridView.CellValueChanged 事件

定义

单元格的值更改时发生。

C#
public event System.Windows.Forms.DataGridViewCellEventHandler CellValueChanged;
C#
public event System.Windows.Forms.DataGridViewCellEventHandler? CellValueChanged;

事件类型

示例

下面的代码示例演示如何使用 CellValueChanged 事件更新 的余额列中 DataGridView的值。 此示例是 事件中提供的更大示例的 SelectionChanged 一部分。

C#
private void DataGridView1_CellValueChanged(
    object sender, DataGridViewCellEventArgs e)
{
    // Update the balance column whenever the value of any cell changes.
    UpdateBalance();
}

private void DataGridView1_RowsRemoved(
    object sender, DataGridViewRowsRemovedEventArgs e)
{
    // Update the balance column whenever rows are deleted.
    UpdateBalance();
}

private void UpdateBalance()
{
    int counter;
    int balance;
    int deposit;
    int withdrawal;

    // Iterate through the rows, skipping the Starting Balance row.
    for (counter = 1; counter < (DataGridView1.Rows.Count - 1);
        counter++)
    {
        deposit = 0;
        withdrawal = 0;
        balance = int.Parse(DataGridView1.Rows[counter - 1]
            .Cells["Balance"].Value.ToString());

        if (DataGridView1.Rows[counter].Cells["Deposits"].Value != null)
        {
            // Verify that the cell value is not an empty string.
            if (DataGridView1.Rows[counter]
                .Cells["Deposits"].Value.ToString().Length != 0)
            {
                deposit = int.Parse(DataGridView1.Rows[counter]
                    .Cells["Deposits"].Value.ToString());
            }
        }

        if (DataGridView1.Rows[counter].Cells["Withdrawals"].Value != null)
        {
            if (DataGridView1.Rows[counter]
                .Cells["Withdrawals"].Value.ToString().Length != 0)
            {
                withdrawal = int.Parse(DataGridView1.Rows[counter]
                    .Cells["Withdrawals"].Value.ToString());
            }
        }
        DataGridView1.Rows[counter].Cells["Balance"].Value =
            (balance + deposit + withdrawal).ToString();
    }
}

注解

提交 DataGridView.CellValueChanged 用户指定的值时发生该事件,这通常在焦点离开单元格时发生。

但是,对于检查框单元格,通常需要立即处理更改。 若要在单击单元格时提交更改,必须处理 DataGridView.CurrentCellDirtyStateChanged 事件。 在处理程序中,如果当前单元格是复选框单元格,请调用 DataGridView.CommitEdit 方法并传入 Commit 值。

更改单元格值时,控件中的行不会自动排序。 若要在用户修改单元格时对控件进行排序,请在事件处理程序中CellValueChanged调用 Sort 方法。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅