2015-04-01 80 views
0

我通過按下tab按鈕以編程方式跳轉到下一行。 如果我想要跳回來,我使用Tab + Shift鍵。 如果按下tab + shift,則rowcount減少2。 當我想從最後一行返回時,索引跳轉到第一個控件,該控件的標籤索引爲0. 最後一行的問題是什麼?C#:在datagridview中獲取行(shift + tab)

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; 
     } 
    } 
+0

兩件事:首先,我沒有想到Tab鍵被KeyDown事件捕獲。其次,如果按下SHIFT + Tab,該方法中的兩個條件都將被滿足 - 即(e.KeyCode == Keys.Tab)和(e.Modifiers == Keys.Shift && e.KeyCode == Keys.Tab )將是真實的。 – Ulric 2015-04-01 09:08:39

+0

我的問題是,標準選項卡分配跳轉到下一個單元格,但我需要跳到下一行,因此我使用keydown事件對其進行了編程。 – 2015-04-01 09:11:40

+0

您是否測試過Tab鍵是否實際觸發KeyDown事件? – Ulric 2015-04-01 09:17:13

回答

2

您遇到的問題是因爲按下SHIFT + Tab時代碼中的兩個條件都會被滿足。

以下代碼在我的機器上正常工作。

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; 
     } 
    } 
} 
+0

謝謝,工作正常:) – 2015-04-01 09:51:03