简体   繁体   中英

C#: get row back in datagridview (shift+tab)

I programmatically jump to the next row by pressing the tab button. If i want do jump back, i use the tab + shift key. If tab + shift is pressed, the rowcount gets reduced by two. When I want to go back from the last row, the index jumps to the first control, which has the tab index of 0. Whats the problem at the last row?

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            row++;
            if (row > dataGridView1.RowCount - 1)
            {
                menuStrip1.Select();
                datensatzToolStripMenuItem.Select();
                dataGridView1.CurrentCell = dataGridView1[0, 0];
            }
            else dataGridView1.CurrentCell = dataGridView1[0, row];
            e.Handled = true;
        }
        if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Tab)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            row -= 2;
            if (row < 0) 
            {
                menuStrip1.Select();
                datensatzToolStripMenuItem.Select();
                dataGridView1.CurrentCell = dataGridView1[0, 0];
            }
            else dataGridView1.CurrentCell = dataGridView1[0, row];
            e.Handled = true;
        }
    }

The problem you are having is because both conditions in your code will be met when SHIFT+Tab is pressed.

The following code works fine on my machine.

private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Tab) {
        if (e.Modifiers != Keys.Shift) {
            int row = dataGridView1.CurrentCell.RowIndex;
            row++;
            if (row > dataGridView1.RowCount - 1) {
                menuStrip1.Select();
                datensatzToolStripMenuItem.Select();
                dataGridView1.CurrentCell = dataGridView1[0, 0];
            }
            else {
                dataGridView1.CurrentCell = dataGridView1[0, row];
            }
            e.Handled = true;
        }
        else {
            int row = dataGridView1.CurrentCell.RowIndex;
            row -= 1;
            if (row < 0) {
                menuStrip1.Select();
                datensatzToolStripMenuItem.Select();
                dataGridView1.CurrentCell = dataGridView1[0, 0];
            }
            else {
                dataGridView1.CurrentCell = dataGridView1[0, row];
            }
            e.Handled = true;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM