DataGridView.CellValueChanged 事件

定義

儲存格的值變更時發生。

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

事件類型

範例

下列程式碼範例示範如何使用 CellValueChanged 事件來更新 餘額資料行 DataGridView 中的值。 此範例是事件中可用的較大範例的 SelectionChanged 一部分。

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

另請參閱