Export (0) Print
Expand All

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 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 void getCurrentCellButton_Click(object sender, System.EventArgs e)
        string msg = String.Format("Row: {0}, Column: {1}",
        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 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];

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.

© 2014 Microsoft