How do I make pressing the Enter key cause focus to move to the cell below like Excel's default behavior?

Blanthor picture Blanthor · Feb 11, 2010 · Viewed 13.1k times · Source

I am using an Infragistics UltraWinGrid v9.1. I want to allow the user to enter numerical data in a cell, press Enter and then have the focus on the cell below, like you see in Excel. It appears that the KeyUp event might be better than the KeyPressed event for this, but I keep throwing an exception that I have gone beyond the bounds of the UltraWinGrid even though I start at the top of a full grid. Here is the code I've tried:

    private void ugrid_KeyUp(object sender, KeyEventArgs e)
    {
        UltraGrid grid = (UltraGrid)sender;

        if (e.KeyCode == Keys.Enter)
        {
            // Go down one row
            UltraGridCell cell = grid.ActiveCell;
            int currentRow = grid.ActiveRow.Index;
            int col = cell.Column.Index;
            grid.Rows[currentRow + 1].Cells[grid.ActiveCell].Activate();
        }
    }

I expected this to make the cell in the same column but one row below to become the active cell with the call, grid.Rows[currentRow + 1].Cells[grid.ActiveCell].Activate();

Instead an exception is thrown:

An exception of type 'System.IndexOutOfRangeException' occurred in Infragistics2.Shared.v9.1.dll but was not handled in user code Additional information: Index was outside the bounds of the array.

Since I'm on row 0 and there exists a row 1 this is a surprise to me. The values for currentRow and col are 0 and 28 respectively. What would be a better approach? btw I can do this again the cell below, where the values are currentRow = 1 and col = 28. The same exception is thrown.

Answer

Blanthor picture Blanthor · Feb 15, 2010

Someone answered my question on the Infragistics fora...

    private void ugrid_KeyUp(object sender, KeyEventArgs e)
    {
        var grid = (UltraGrid)sender;

        if (e.KeyCode == Keys.Enter)
        {
            // Go down one row
            grid.PerformAction(UltraGridAction.BelowCell);
        }
    }