Share via


How to: Get and Set the Current Cell in the Windows Forms DataGridView Control

Interaction with the DataGridView often requires that you programmatically discover which cell is currently active. You may also need to change the current cell. You can perform these tasks with the CurrentCell property.

Note

You cannot set the current cell in a row or column that has its Visible property set to false.

Depending on the DataGridView control's selection mode, changing the current cell can change the selection. For more information, see Selection Modes in the Windows Forms DataGridView Control.

To get the current cell programmatically

  • Use the DataGridView control's CurrentCell property.

    Private Sub getCurrentCellButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles getCurrentCellButton.Click
    
        Dim msg As String = String.Format("Row: {0}, Column: {1}", _
            dataGridView1.CurrentCell.RowIndex, _
            dataGridView1.CurrentCell.ColumnIndex)
        MessageBox.Show(msg, "Current Cell")
    
    End Sub
    
    private void getCurrentCellButton_Click(object sender, System.EventArgs e)
    {
        string msg = String.Format("Row: {0}, Column: {1}",
            dataGridView1.CurrentCell.RowIndex,
            dataGridView1.CurrentCell.ColumnIndex);
        MessageBox.Show(msg, "Current Cell");
    }
    

To set the current cell programmatically

  • Set the CurrentCell property of the DataGridView control. In the following code example, the current cell is set to row 0, column 1.

    Private Sub setCurrentCellButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles setCurrentCellButton.Click
    
        ' Set the current cell to the cell in column 1, Row 0. 
        Me.dataGridView1.CurrentCell = Me.dataGridView1(1, 0)
    
    End Sub
    
    private void setCurrentCellButton_Click(object sender, System.EventArgs e)
    {
        // Set the current cell to the cell in column 1, Row 0. 
        this.dataGridView1.CurrentCell = this.dataGridView1[1,0];
    }
    

Compiling the Code

This example requires:

  • Button controls named getCurrentCellButton and setCurrentCellButton. In Visual C#, you must attach the Click events for each button to the associated event handler in the example code.

  • A DataGridView control named dataGridView1.

  • References to the System and System.Windows.Forms assemblies.

See Also

Reference

DataGridView

DataGridView.CurrentCell

Concepts

Selection Modes in the Windows Forms DataGridView Control

Other Resources

Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control