globetrotter
globetrotter

Reputation: 1047

Capture Keys.Down and Keys.Up on dataGridview_KeyDown

I have a DataGridView where each of its rows' indexes correspond to an index in a List<SomeClass>, e.g. second row of the DataGridView corresponds to List[1] (counting from zero), etc. When the user clicks on column 0 of dataGridView1, I display List[e.RowIndex] on another DataGridView like this:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        dataGridView2.Rows.Clear();
        if (e.RowIndex >= 0 && !dataGridView1.Rows[e.RowIndex].IsNewRow)
        {
            for (int j = 0; j < Data[e.RowIndex].Values.Count; j++)
            {
                //add Data[e.RowIndex].Values to dataGridView2
            }
        }
    }
}

This works fine and I am trying to implement the same thing but this time using the up and down keys of the keyboard using the KeyDown event:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down && dataGridView1.CurrentCell.ColumnIndex == 0)            
    {
        if (dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex - 1].IsNewRow)
        {
            dataGridView2.Rows.Clear();
            e.Handled = true;
        }                
        if (!dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + 1].IsNewRow) 
        {
            dataGridView2.Rows.Clear();
            for (int j = 0; j < Data[dataGridView1.CurrentCell.RowIndex + 1].Values.Count; j++)
            {
                //add Data[dataGridView1.CurrentCell.RowIndex + 1].Values to dataGridView2
            }
        }
    }
    else if (e.KeyCode == Keys.Up && dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        if (dataGridView1.CurrentCell.RowIndex > 0)
        {
            dataGridView2.Rows.Clear();
            for (int j = 0; j < Data[dataGridView1.CurrentCell.RowIndex - 1].Values.Count; j++)
            {
                //add Data[dataGridView1.CurrentCell.RowIndex - 1].Values to dataGridView2
            }
        }
    }
}

This works but produces an

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

error, in the 2nd if, on the following two cases:

I seem to be missing out something here, could anyone help me or point me to the right direction?

Upvotes: 0

Views: 2723

Answers (1)

Brian Green
Brian Green

Reputation: 567

I was having this issue too and in case there is anyone out there like me, who typically ignores comments and only looks for answers, Hans Passant's comment

"Overriding keyboard handling in DGV is very troublesome. Use the RowEnter event instead. – Hans Passant Feb 15 '12 at 2:47"

is one correct solution.

Upvotes: 1

Related Questions