首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# WinForms TextBox 按鍵控制 DataGridView 焦點移動:KeyDown 事件實現上下鍵選列

     編輯:程式設計綜合問答

需求:游標停留在 TextBox 時,按 ↑/↓ 鍵讓 DataGridView 選中上/下一列,TextBox 保持焦點。

實作代碼

private void textBox1_KeyDown(object sender, KeyEventArgs e) {
    if (dataGridView1.Rows.Count == 0) return;
    int currentIndex = dataGridView1.CurrentCell?.RowIndex ?? -1;
    if (currentIndex < 0) return;

    int targetIndex = currentIndex;
    if (e.KeyCode == Keys.Down) targetIndex = Math.Min(currentIndex + 1, dataGridView1.Rows.Count - 1);
    else if (e.KeyCode == Keys.Up) targetIndex = Math.Max(currentIndex - 1, 0);
    else return;

    dataGridView1.ClearSelection();
    dataGridView1.Rows[targetIndex].Selected = true;
    dataGridView1.CurrentCell = dataGridView1.Rows[targetIndex].Cells[0];
    e.Handled = true; // 防止 TextBox 內部游標移動
}

關鍵點

  • 使用 KeyDown 而非 KeyPress 以捕獲方向鍵。
  • e.Handled = true 避免 TextBox 吃掉按鍵導致游標跳動。
  • 檢查 CurrentCell 為 null 防呆。
  • 若需同步捲動,加上 dataGridView1.FirstDisplayedScrollingRowIndex = targetIndex;。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved