SoFunction
Updated on 2025-03-07

C# operation DataGridView to get or set the content of the current cell

The current cell refers to the cell where the DataGridView focuses, which can be obtained through the CurrentCell property of the DataGridView object. If the current cell does not exist, return null.

Get the contents of the current cell:

object obj = this.dgv_PropDemo.;

Note: The return value is of type object.

Get the column index of the current cell:

int columnIndex = this.dgv_PropDemo.;

Get the index of the row where the current cell is located:

int rowIndex= this.dgv_PropDemo.;

Also, use properties to determine the row where the cell resides:

int row= this.dgv_PropDemo.;

List:

int column = this.dgv_PropDemo.;

Note: The indexes of rows and columns of DataGridView start from 0.

The current cell can be changed by setting the CurrentCell of the DataGridView object.

=DataGridView1[int columnIndex,int rowIndex];

Note: If the selected mode of DataGridVIew is a row selection, the entire row of the current cell will be selected. Otherwise, only the current cell that is set will be selected.

Setting CurrentCell to Null can deactivate the current cell.

Example: Set the first row and second column to the current CurrentCell

this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[1, 0];

Example: traversing DataGridView by up and down implementation

/// <summary>
        /// traversal upwards        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Up_Click(object sender, EventArgs e)
        {
            //Get the index of the previous line            int upRowIndex = this.dgv_PropDemo. - 1;
            if (upRowIndex < 0)
            {
                //Select the last line                this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, this.dgv_PropDemo.RowCount - 1];
            }
            else
            {
                this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, upRowIndex];
            }
        }

        /// <summary>
        /// traverse downward        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Down_Click(object sender, EventArgs e)
        {
             //Get the index of the next line            int nextRowIndex = this.dgv_PropDemo. + 1;
            if (nextRowIndex > this.dgv_PropDemo.RowCount - 1)
            {
                this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, 0];
            }
            else
            {
                this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, nextRowIndex];
            }
        }

This is the end of this article about C# manipulating DataGridView to get or set the current cell content. I hope it will be helpful to everyone's learning and I hope everyone will support me more.