How to set the current row on a DataGridView

Now here’s one that I thought I had done before, but came back to bite me in the butt. Here’s the usual situation:

You’ve got a dialog that has a DataGridView. For whatever reason you need to make it go to a particular row in the grid. (For example, you’ve selected something else in a list, and you want to make sure that that particular related record in the grid is visible).

Here’s what you’d probably think of doing:


//where "i" is the index of the row you want to select...
dataGridView.CurrentCell = dataGridView.Rows[i].Cells[0];

Now this works all dandy and fine, until you start editing the contents of some of the rows. Up pops an exception:

Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.

Hmm, not cool. So, what’s the workaround? Try something like this:


dataGridView.FirstDisplayedScrollingRowIndex = i;

That should make the first visible row in your DataGridView the row that you were wanting to be displayed. Note that it won’t select it, but at least it will be visible. This sort of thing is useful when you want to make a certain row visible, such as a row that has an error.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s