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
{
gr
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
Eventually the last row is empty because it's the empty row with which the user can add a new row. This row cannot be selected. Have you tried grid.Rows.Count - 2? As an alternative, you can set AllowUserToAddRows to false.
Your 'catch' block for IndexOutOfRangeException is empty, and will not display any error at all.
Either your question is not exact, or the exception is being thrown somewhere else.
EDIT: Having looked through your call stack that you added, I can see that the error is, indeed, not being thrown here, but rather in the CurrencyManager
class's Current
/Item
properties, which is ultimately being triggered by the call to the CurrentCell
setter.
Bottom line: the problem is not in this code; the exception is being thrown by some other piece of code triggered by your setting the current cell.
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)
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
To avoid the IndexOutOfRangeException make sure only to select a visible row. I suggest:
// Find last visible row
DataGridViewRow row = dataGridView1.Rows.Cast<DataGridViewRow>().Where(r => r.Visible).Last();
// scroll to last row if necessary
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.IndexOf(row);
// select row
row.Selected = true;