Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > DataGridView - Select row programatically
 

DataGridView - Select row programatically

How can I programatically make a row in a DataGridView selected? The SelectedRows property is read only.
Foss  Friday, January 20, 2006 12:03 PM

"Rows" is a property of the DataGridView that returns all the rows as a collection. For a particular Row, you can set the .Selected property to True (or False) to select (or unselect) that Row.

For example,

dgv = new DataGridView

.

.

.

dgv.Rows(index).Selected = True

Matty4242  Friday, January 20, 2006 8:52 PM

I've worked it out.

I need to make the row the current row.

CurrentRow is readonly, but setting the current cell has the desired effect.

Phil Rogers  Monday, May 22, 2006 12:01 PM

"Rows" is a property of the DataGridView that returns all the rows as a collection. For a particular Row, you can set the .Selected property to True (or False) to select (or unselect) that Row.

For example,

dgv = new DataGridView

.

.

.

dgv.Rows(index).Selected = True

Matty4242  Friday, January 20, 2006 8:52 PM

I had a similar problem, which this almost solved.

The row gets selected, (the cells in the row are highlighted), but the little black arrow in the column to the left of the data stays at the previously selected row.

How do I get it to update that as well?

Phil Rogers  Monday, May 22, 2006 11:18 AM

The DataGridView can contain multiple SELECTED rows (if you set property MultiSelect to True) but should only contain a single CurrentCell - this is the cell that is currently active (being edited for example). Set the CurrentCell property to a non-hidden non-disabled, non-header cell and that will move the black arrow to the row that contains that cell. This row can be checked with the CurrentRow (read-only) property of the dgv.

For example in VB:

DataGridView1.CurrentCell = DataGridView1.Rows(1).Cells(0)

Hope this helps.

PS Best to put separate issues on separate threads - you can always reference one thread from another using a hyperlink.

Matty4242  Monday, May 22, 2006 12:00 PM

I've worked it out.

I need to make the row the current row.

CurrentRow is readonly, but setting the current cell has the desired effect.

Phil Rogers  Monday, May 22, 2006 12:01 PM

When I try to set the CurrentCell property I get this error "Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function"

Any clue how to fix this?....

Shammi Jayaraj  Wednesday, May 24, 2006 5:37 PM

In what event or method do you set the CurrentCell property? Is it possible, albeit farfetched, that the method that sets the property is being executed as a result of the current cell being changed?

Just a stab.

Matty4242  Wednesday, May 24, 2006 10:18 PM
Not sure if this will solve your problem, but I set the row after the binding is complete in the DataBindingComplete event.

Here's my code:

private void DataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
// this is the row you want selected programatically
int RowYouWantToSelect;

// get the rowcount
int rowCount = dgv_FinancialList.RowCount;

// set a flag for existance of row
bool rowExists = false;

// loop through the rows in the data grid
for (int i = 0; i < rowCount; i++)
{
// check to see if this is the row you want to remember
if (Convert.ToInt32(DataGridView.RowsIdea.Cells["ID_Field"].Value) == RowYouWantToSelect)
{
// set CurrentCell equal to this row, you can choose any cell in the row
DataGridView.CurrentCell = DataGridView.RowsIdea.Cells[0];

// set flag for existance of row
rowExists = true;

// break out, you don't need to loop anymore
break;
}
}

// if row does not exist, set current cell to first row.
if (!rowExists)
{
DataGridView.CurrentCell = DataGridView.Rows[0].Cells[0];
}
}
Hank2  Thursday, July 20, 2006 3:06 PM

Thanks for the post Hank. I just wanted to add one additional point -- when setting the CurrentCell property, it's important that the Cells[x] that is chosen is visible. If it is hidden, then an exception will be thrown.

Grant Szabo  Wednesday, August 09, 2006 8:09 PM

Hi,

Just stumbled across this thread, as it's exactly the problem I'm now trying to solve. All good, except for one point. My datagridview is large enough that the record I'm trying to refocus on is off the screen. i.e. the cell is not visible.

How do I get round this?

Cheers.

High Hat  Thursday, August 10, 2006 11:37 AM

Ahh, don't worry, I've figured it out. I need to force a scroll and redraw first, then set the current row/cell;

DataGridView1.FirstDisplayedScrollingRowIndex = DataGridView1.Rows(counter).Index

DataGridView1.Refresh()

DataGridView1.CurrentCell = DataGridView1.Rows(counter).Cells(1)

DataGridView1.Rows(counter).Selected = True

High Hat  Thursday, August 10, 2006 12:34 PM

This has been a helpful thread.

Thanks to all contributors.

James Collett  Tuesday, July 10, 2007 1:03 PM

I have a slightly different question along these lines if someone can help me out.

I have a multi-select datagridview. I have added a contextmenu to my rows when adding them based on a column value. I only allow a row selection. When you right click on the row, the contextmenu pops up, but it does NOT select the row that was right clicked on.

I solved this problem by checking the mousedown event, checking to see if it was the right mouse button that was clicked and then selecting the row. The result is like a multi-select selection with the CTRL key pressed. If the SHIFT key is pressed it works the same way, which is not correct.

I started writing all kinds of code to make the right click to perform the multi-select in all cases like a left click before popping up my contextmenu. I'm having a hard time doing this and it seems the wrong approach.

I want the right click to behave like the left click (select row and perform correctlyfor multi-select)and then pop open the contextmenu.

Anyone know how to do this?

Thanks!

Hubman  Thursday, September 20, 2007 10:13 PM

See if this thread helps you out make sure you read the second post and the one from "dd3" on 5-11-07

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=196286&SiteID=1

Matty4242  Friday, September 21, 2007 3:16 AM
I think this will help, use the context menu opening event. This way the position of the contect menu is at the mouseposition automatically. The cell iss selected to get the rowpointer moved. The the row gets selected.

private void cmuGrid_Opening(object sender, CancelEventArgs e)

{

// get the mouse porsition and convert it to coordinate within the grid

Point pt = grdJobs.PointToClient(MousePosition);

// now get the testinfo at the gridcoordinate

DataGridView.HitTestInfo hti = grdJobs.HitTest(pt.X, pt.Y);

// is it a cell?

if (hti.Type == DataGridViewHitTestType.Cell)

{

// make the cell the current on and select the row

grdJobs.ClearSelection();

grdJobs.CurrentCell = grdJobs.Rows[hti.RowIndex].Cells[hti.ColumnIndex];

grdJobs.Rows[hti.RowIndex].Selected = true;

// do whatever you want to do, set contextmenu text for example

}

}

Eric-Jan  Friday, November 30, 2007 9:30 AM
I think this will help, use the context menu opening event. This way the position of the contect menu is at the mouseposition automatically. The cell iss selected to get the rowpointer moved. The the row gets selected.

private void cmuGrid_Opening(object sender, CancelEventArgs e)

{

// get the mouse porsition and convert it to coordinate within the grid

Point pt = grdJobs.PointToClient(MousePosition);

// now get the testinfo at the gridcoordinate

DataGridView.HitTestInfo hti = grdJobs.HitTest(pt.X, pt.Y);

// is it a cell?

if (hti.Type == DataGridViewHitTestType.Cell)

{

// make the cell the current on and select the row

grdJobs.ClearSelection();

grdJobs.CurrentCell = grdJobs.Rows[hti.RowIndex].Cells[hti.ColumnIndex];

grdJobs.Rows[hti.RowIndex].Selected = true;

// do whatever you want to do, set contextmenu text for example

}

}

Eric-Jan  Friday, November 30, 2007 9:31 AM

Just started using this code for the above multi-select row feature. Only immediate bug: If you move the mouse real fast, some rows get skipped. Butonly 'real' fast.

void Grid_MouseDown(object sender, MouseEventArgs e)

{

DataGridView.HitTestInfo hti = Grid.HitTest(e.X, e.Y);

if (e.Button == MouseButtons.Right && hti.Type == DataGridViewHitTestType.Cell)

{

if(Control.ModifierKeys != Keys.Control)

{

Grid.ClearSelection();

}

Grid.MouseMove += new MouseEventHandler(m_pinGrid_MouseMove);

Grid.Rows[hti.RowIndex].Cells[hti.ColumnIndex].Selected = true;

}

}

void Grid_MouseMove(object sender, MouseEventArgs e)

{

DataGridView.HitTestInfo hti = Grid.HitTest(e.X, e.Y);

if (e.Button == MouseButtons.Right && hti.Type == DataGridViewHitTestType.Cell)

{

m_pinGrid.Rows[hti.RowIndex].Cells[hti.ColumnIndex].Selected = true;

}

}

void Grid_MouseUp(object sender, MouseEventArgs e)

{

DataGridView.HitTestInfo hti = Grid.HitTest(e.X, e.Y);

if (e.Button == MouseButtons.Right)

{

Grid.MouseMove -= new MouseEventHandler(Grid_MouseMove);

}

}

nemoy34  Wednesday, December 12, 2007 4:50 PM
hi, I have a similar problem,
everything a set of value is insert to my table then display on DataGridview
when everytime the datagridview refresh, how do I make the datagridview select the last (latest) entry???
The-another-guy  Thursday, May 08, 2008 4:21 AM

You can change the sorting order

or

Code Snippet

// grdOutput = the grid

// GotoGridEnd = a boolean whether or not to scroll to the end

if ((GotoGridEnd) && (grdOutput.RowCount > grdOutput.DisplayedRowCount(true)))
{
grdOutput.FirstDisplayedScrollingRowIndex = grdOutput.RowCount -grdOutput.DisplayedRowCount(true);
}

Eric-Jan  Tuesday, May 13, 2008 9:05 AM

This is a very helpful thread. Really appreciate help of all contributors.

Kaushik Patel  Wednesday, June 11, 2008 8:30 AM

I was a bit surprised that no method exists to carry out this common task froma few parameters like column and lookup value.

My solution learned from this thread (thanks to all) may be useful for others so here it is.

Code Snippet

// Clear previous selection(s).

dataGridView1.ClearSelection();

// Set product no. to look up.

_productNo = _productRow.ProductNo;

// Column of ProductNo.

int colProductNo = 1;

int rowCount = dataGridView1.Rows.Count;

// Look up and select product number in the DataGridview.

DataGridViewRow row = new DataGridViewRow();

for (int i = 0; i < rowCount; i++)

{

row = dataGridView1.Rows[i];

if (row.Cells[colProductNo].Value.Equals(_productNo))

{

// Bring found row near top of list.

dataGridView1.FirstDisplayedScrollingRowIndex = i;

// Select the found row.

dataGridView1.CurrentCell = row.Cells[colProductNo];

row.Selected = true;

// Exit the loop.

break;

}

}

if (row.Selected)

{

// Do more stuff.

}

/gustav

Cactus Data  Saturday, July 12, 2008 6:48 PM

This information helped me get the programatically selected row displayed, but the scroll bar slider is not positioned correctly. I added a new row to the bottom of the grid programatically and the code sample code helped me get the new row displayed. However, the scroll bar slider is positioned at the top of the scroll bar instead of the bottom. As soon as the user takes some action that causes the grid to adjust (move to a different row, sort, etc.), the slider jumps to the proper position. Is there some way to programatically reset the slider?

Helfrich  Wednesday, August 13, 2008 6:52 PM
How about calling

dataGridView1.Refresh();

?

/gustav
Cactus Data  Saturday, September 20, 2008 9:11 PM
I know this is an old thread, but i wanted to say thanks to everyone that contributed. It helped me a lot with my program! :)
Energizer84  Thursday, April 16, 2009 9:19 PM
I really appreciate this thread, but i do not seem to make it work for me.

I get an error messagethat "... GridViewRow does not contain a definition for Selected ...". Here is my code. Everything except the line with Selected works.

protected void gvwNavButtons_DataBound(object sender, EventArgs e)

{

if (gvwNavButtons.Rows.Count == 1)

{

gvwNavButtons.Rows[0].Selected =

true;

gvwNavButtons.Visible = false;

}
}

My goal is to
1) when there is only a single record returned
2) select the row. The queries for other GridViews are dependant on which row is selected
3) make the GridView hidden
4) do other things

Can anyone shed some light on why i get this error message? it seems so straight forward and others seem to be using this syntax.

Thanks
Jon

JonAtHome  Tuesday, May 05, 2009 11:35 PM
I'd like to note something. I'm doing something similar to all of you, but using SINGLE SELECT rows in the DataGridView.

I'm developing a software like the "Microsoft Training Kits" but using files from braindumps dot com. I adapt them to fit in a xml file and an application will compare your answers with those from the xml file (application calculates your score, randomizes questions, limits your time, and things like that).

Initially, I've used a listbox to ennumerate questions. But I've decided to replace it by a DataGridView just because I wanted an icon next to the question list to see which answers were Ok, bad or empty. I wanted to do that way just because I needed to gain knowledge of using image columns and a few topics more.

You can navigate the question list with your mouse, but certain frantic people like me, wants to navigate with keyboard shortcuts. So I created two methods: one for going forward and another going backward. Of course, it just could be one.

I didn't realized why the rows weren't painted "blue" when changing selection... and no row were selected after all...

This is what happens: when you set the DataGridView to SINGLE SELECT, at all times there must be a single row selected. My methods first check selected row, select next or previous row, and then deselected the old row. This is wrong, because for a lilttle time, two rows where selected at once. DataGridView does not throw an exception, and no error were showing anywhere.

Conclusion: if you need to navigate between rows, first store the selected index, then use DataGridView.ClearSelection() and then select the row you need. That, of course, is what it works.


I hope this will help someone who had the same problem I had.

Ing Rosell
fabrosell  Wednesday, September 09, 2009 6:58 PM

You can use google to search for other answers

Custom Search

More Threads

• Geting a reference to new record
• Display Blobs on Reports??
• Edit a control in a DataGridView
• Binding DataGridView to XML node or document
• insertion event handler
• DataGridView and an empty ComboBox
• Display Nested Structure Array in DataGridView
• .net 1.1 - datagrid -"endedit" problem -Still Exist
• How to validate UK postcode in vb
• Problem with Databinding combobox