共用方式為


HOW TO:依據 Windows Form DataGridView 控制項儲存格的變更執行自訂動作

更新:2007 年 11 月

DataGridView 控制項具有許多事件,您可用這些事件來偵測在 DataGridView 儲存格狀態中的變更。最常用的兩個事件是 CellValueChangedCellStateChanged 事件。

若要偵測 DataGridView 儲存格值的變更

  • 撰寫 CellValueChanged 事件的處理常式。

    Private Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles dataGridView1.CellValueChanged
    
        Dim msg As String = String.Format( _
            "Cell at row {0}, column {1} value changed", _
            e.RowIndex, e.ColumnIndex)
        MessageBox.Show(msg, "Cell Value Changed")
    
    End Sub
    
    private void dataGridView1_CellValueChanged(object sender,
        DataGridViewCellEventArgs e)
    {
        string msg = String.Format(
            "Cell at row {0}, column {1} value changed",
            e.RowIndex, e.ColumnIndex);
        MessageBox.Show(msg, "Cell Value Changed");
    }
    

若要偵測 DataGridView 儲存格狀態的變更

  • 撰寫 CellStateChanged 事件的處理常式。

    Private Sub dataGridView1_CellStateChanged(ByVal sender As Object, _
        ByVal e As DataGridViewCellStateChangedEventArgs) _
        Handles dataGridView1.CellStateChanged
    
        Dim state As DataGridViewElementStates = e.StateChanged
        Dim msg As String = String.Format( _
            "Row {0}, Column {1}, {2}", _
            e.Cell.RowIndex, e.Cell.ColumnIndex, e.StateChanged)
        MessageBox.Show(msg, "Cell State Changed")
    
    End Sub
    
    private void dataGridView1_CellStateChanged(object sender,
        DataGridViewCellStateChangedEventArgs e)
    {
        DataGridViewElementStates state = e.StateChanged;
        string msg = String.Format("Row {0}, Column {1}, {2}",
            e.Cell.RowIndex, e.Cell.ColumnIndex, e.StateChanged);
        MessageBox.Show(msg, "Cell State Changed");
    }
    

編譯程式碼

這項範例需要:

請參閱

工作

逐步解說:驗證 Windows Form DataGridView 控制項中的資料

參考

DataGridView

DataGridView.CellValueChanged

DataGridView.CellStateChanged

其他資源

在 Windows Form DataGridView 控制項中利用儲存格、資料列和資料行進行程式設計