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

EDIT:

Here is the complete exception:

System.IndexOutOfRangeException: Index -1 does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get_Current()
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell value)
9
задан Irshad 25 September 2017 в 07:12
поделиться