Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView navigating to next row

I have a C# winforms application and I am trying to get a button working that will select the next row in a datagridview after the one curently selected.

The code I have so far is:

private void button4_Click(object sender, EventArgs e)
{
  try
  {
    Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);

    // index out of range on this line
    dataGridView1.Rows[dataGridView1.SelectedRows[selectedRowCount].Index].Selected = true;

    dataGridView1.FirstDisplayedScrollingRowIndex = selectedRowCount + 1;
  }
  catch (Exception ex)
  {
    return;
  }

But on running this it throws an exception. Could anyone point out where I may be going wrong. The thrown error is: Index is out of range

like image 807
Daniel Flannery Avatar asked Dec 16 '22 22:12

Daniel Flannery


1 Answers

try this:

 int nRow;
private void Form1_Load(object sender, EventArgs e)
{

    nRow = dataGridView1.CurrentCell.RowIndex;
}

private void button1_Click(object sender, EventArgs e)
{
    if (nRow < dataGridView1.RowCount )
    {
        dataGridView1.Rows[nRow].Selected = false;
        dataGridView1.Rows[++nRow].Selected = true;
    }
}
like image 197
KF2 Avatar answered Dec 30 '22 11:12

KF2