Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 760
Martijn Avatar asked Sep 28 '10 07:09

Martijn


2 Answers

Try:

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)

alt text

like image 173
KMån Avatar answered Oct 23 '22 09:10

KMån


Have you thought about using Linq for this?

    grid.Rows.OfType<DataGridViewRow>().Last().Selected = true;
    grid.CurrentCell = grid.Rows.OfType<DataGridViewRow>().Last().Cells.OfType<DataGridViewCell>().First(); // if first wanted
like image 20
danijels Avatar answered Oct 23 '22 10:10

danijels