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 Rows
collection 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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With