如何:根据 Windows 窗体 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 窗体 DataGridView 控件中的数据

参考

DataGridView

DataGridView.CellValueChanged

DataGridView.CellStateChanged

其他资源

使用 Windows 窗体 DataGridView 控件中的单元格、行和列编程