none
DataGridView - Select row programatically

    Question

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

Answers

  • "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

    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.

     

     

    Monday, May 22, 2006 12:01 PM

All replies

  • "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

    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?

    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.

    • Proposed as answer by Jared Busch Wednesday, January 06, 2010 9:39 PM
    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.

     

     

    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?....

    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.

    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];
    }
    }
    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.

     

    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.

    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

    Thursday, August 10, 2006 12:34 PM
  • This has been a helpful thread.

     

    Thanks to all contributors.

     

    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 correctly for multi-select) and then pop open the contextmenu. 

     

    Anyone know how to do this?

     

    Thanks!

    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

     

    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

     

    }

    }

    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

     

    }

    }

    • Proposed as answer by djm10 Wednesday, June 27, 2012 10:11 AM
    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.  But only '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);

    }

    }

    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???
    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);
    }

     

     

    Tuesday, May 13, 2008 9:05 AM
  • This is a very helpful thread. Really appreciate help of all contributors.

    Wednesday, June 11, 2008 8:30 AM
  • I was a bit surprised that no method exists to carry out this common task from a 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

    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?

     

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

    dataGridView1.Refresh();

    ?

    /gustav
    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! :)
    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 message that "... 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

    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
    Wednesday, September 09, 2009 6:58 PM
  • Set BindingSource's position to CurrentRow's index to make it active row.


    ((BindingSource)someDataGridView.DataSource).Position = someDataGridView.CurrentRow.Index;
    Friday, December 18, 2009 11:18 PM
  • Not sure if this is the correct place for this post or even if anyone is still monitoring the thread....

    My DGV has blank cells which is fine they are not compulsary and i dont have a problem with them.
    I can't select a blank cell. In fact i can't even select the area around a populated cell.
    Anyone else seen this and have i just missed a simple property?

    Thanks

    J
    Thursday, January 14, 2010 3:00 PM
  • How can I programatically make a row in a DataGridView selected? The SelectedRows property is read only.


    I have created the following extension method to achieve my result. It works for "full row select" / "single selection" configured DataGridViews, with databound items.

    public static void SelectRow<T>(this DataGridView dgv, T selectedItem) where T : class
    {
    	foreach (DataGridViewRow row in dgv.Rows)
    	{
    		if ((row.DataBoundItem as T) == selectedItem)
    		{
    			dgv.CurrentCell = row.Cells[0];
    			break;
    		}
    	}
    }

     

    • Proposed as answer by tonbr Tuesday, April 27, 2010 9:56 PM
    Tuesday, April 27, 2010 9:55 PM
  • Thanks buddy.... it's worked out to me.....
    Monday, August 16, 2010 10:24 AM
  • I know the thread is quite old, just wanted to thank you all guys.

    It's been a (long-long) while since I didn't make any code, so sometimes I have to look after how things work.

    Thanks a lot.

    long-long means two digits in years:) 

     

    Monday, May 30, 2011 6:34 PM
  • Old post, but still very helpful, although I think a very important point has been missed.

    What I think has not been mentioned about the record selector arrow is that it will respond to the selection on the underlying data source. So you can select a GridView row with:

    gridView1.Rows[index].Selected = true;

    but the record selector will continue pointing to the selected record in the underlying data source.

    To then make the record pointer point to the selected row you must also perform a

    dataSource.Position = index;

    matching the record selected in the GridView control. You can also use the Move methods.

    Sunday, November 06, 2011 6:04 PM
  • thx to Phil Rogers, that helped me

    I used something like

    mydgv.Rows[dseiredRowNbr].Selected = true;

    mydgv.CurrentCell = myDgv.Rows[dseiredRowNbr].Cells[0];

    I missed Ckuper's selector method of

        myDgv.DataSource.Position = desiredRowNbr

    until after I post the and edit out typo

    however for people working on some generic datagridview passed to a memeber, Phill's idea is a bit quicker and easie as one may not know the eaxact binding source but have to resort to something like 

    mydgv.Rows[desiredRowNbr].Selected = true;
    ((BindingSource)mydgv.DataSource).Position = desiredRowNbr;
    
    I like Phil's idea as I find it easier to type [ or ] instead of ( or )



    • Edited by fs - ab Thursday, July 05, 2012 6:44 PM
    Thursday, July 05, 2012 6:18 PM
  • you can use following code.

    dgv.ClearSelection();

    dgv.Refresh();

    dgv.Rows[index].Cells[index].Selected = True

    Multiselect property in my case is False, and SelectionMode should me full row select. 

    This code worked for me.

    Thanks

    Ashok Tewatia

    Thursday, December 06, 2012 2:53 PM
  • Syntax error, should be:

    dgv.Rows[index].Selected = true;


    • Edited by Storkk Friday, May 23, 2014 12:11 AM
    Friday, May 23, 2014 12:10 AM
  • How can I programatically make a row in a DataGridView selected? The SelectedRows property is read only.
    i agree with Matt
    Tuesday, August 26, 2014 12:24 PM