User Tools

Site Tools

blog:2024-12-11-002



2024-12-11 C#: DatagridView Select last row

  • I have some trouble with setting the last row in my datagridview selected. I select the last row this way:
    if (grid.Rows.Count > 0)
    {
        try
        {
            grid.Rows[grid.Rows.Count - 1].Selected = true;
            grid.CurrentCell = grid.Rows[grid.Rows.Count - 1].Cells[1]
        }
        catch (IndexOutOfRangeException)
        { }
        catch (ArgumentOutOfRangeException)
        { }
    }
  • When I execute this code I get an exception:
    • IndexOutOfRangeException occurred: Index-1 does not have a value.
  • When I debug the Rowscollection and the corresponding Cells collection I see both collections are filled. The index also exists of the Rows and Cells collection.
  • I have no clue what I am doing wrong here. Someone who can help me out here? Thnx

Solution

  • dataGridView1.ClearSelection();//If you want
    
    int nRowIndex = dataGridView1.Rows.Count - 1;
    int nColumnIndex = 3;
    
    dataGridView1.Rows[nRowIndex].Selected = true;
    dataGridView1.Rows[nRowIndex].Cells[nColumnIndex].Selected = true;
    
    //In case if you want to scroll down as well.
    dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
  • Gives following output: (Last row, scrolled and selected)

TAGS

  • 4 person(s) visited this page until now.

Permalink blog/2024-12-11-002.txt · Last modified: 2024/12/11 09:26 by jethro

oeffentlich