Saturday, September 5, 2009

Set focus on DataGridView cell

Setting the focus on a DataGridView cell is a little bit tricky, so this is how you can do it:

Set focus on a DataGridView cell

This code sample will set the editing cursor right in the first cell of the current row in DataGridView. The cell will be ready to get its new data.

C#

DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow;

rowToSelect.Selected = true;

 

rowToSelect.Cells[0].Selected = true;

this.dgvJobList.CurrentCell = rowToSelect.Cells[0];


Auto select the DataGridView cell content

If the focused cell already contains some data an you want to auto select the cell's content right after got the focus, you have to add the "BeginEdit" line, like below:

C#

DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow;

rowToSelect.Selected = true;

 

rowToSelect.Cells[0].Selected = true;

this.dgvJobList.CurrentCell = rowToSelect.Cells[0];

this.dgvJobList.BeginEdit(true);

kick it on DotNetKicks.com

6 comments:

Anonymous said...

Hi thanks for the code snippet it helped me and save my time

Anonymous said...

hi when i am try this code it shows the messge "Current cell can not invisible" pls send the reply ASAP.

Anonymous said...

Thx, gave me a nice pointer at what to try.

Anonymous said...

awsome dude!!
i was able to setfocus, but not able to start editing by default. I had to again click on the cell to start editing.

this is cool.
God bless you.

Anonymous said...

thanks for this ...

Anonymous said...

tnx it such a big help :)