Search code examples
c#winformsdatagridview

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


Solution

  • 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;
        }
    }