选项卡索引在 datagridview 行中循环,不会以 windows 形式移动到下一个控件,c#

Tab Indexing is circulating in datagridview rows not moving to next control in windows form, c#

如果tab索引在datagridview的最后一行和最后一列,如果我此时按下tab键,它会移动到datagridview的第一行和第一列,而不是下一个控件(按钮)。有人可以建议我如何停止最后一行的选项卡索引并移至下一个控件。我试过这段代码。

private void dgCoreRoutes_KeyUp(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.Tab)
   {
     if (dgCoreRoutes.CurrentCell.RowIndex == dgCoreRoutes.Rows.Count-1)
     {
         dgCoreRoutes.TabStop = true;
     }
     if (dgCoreRoutes.CurrentCell.ReadOnly)
     {
        dgCoreRoutes.CurrentCell = GetCoreRoutesGridNextCell(dgCoreRoutes.CurrentCell);
        e.Handled = true;
     }
}

private DataGridViewCell GetCoreRoutesGridNextCell(DataGridViewCell currentCell)
{
     int i = 0;
     DataGridViewCell nextCell = currentCell;
     do
     {
       int nextCellIndex = (nextCell.ColumnIndex + 1) % dgCoreRoutes.ColumnCount;
       int nextRowIndex = nextCellIndex == 0 ? (nextCell.RowIndex + 1) % dgCoreRoutes.RowCount : nextCell.RowIndex;
       nextCell = dgCoreRoutes.Rows[nextRowIndex].Cells[nextCellIndex];
       i++;
     } 
     while (i < dgCoreRoutes.RowCount * dgCoreRoutes.ColumnCount && nextCell.ReadOnly);
     return nextCell;
}

据投资,当你在dataGridView中编辑一个单元格时,可能有另一个控件供你编辑,所以我们无法在KeyUp或keydown方法中获取Tab键事件。

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
 {
    if (keyData == Keys.Tab && dgCoreRoutes.CurrentCell.RowIndex == dgCoreRoutes.Rows.Count-1)
    {
       dgCoreRoutes.TabStop = true;
       //return true;
       //Use standardTab = true; if you want to tab only standard columns and not cells.
    }


else if (keyData == Keys.Tab && dgCoreRoutes.CurrentCell.ReadOnly)
{
       dgCoreRoutes.CurrentCell = GetCoreRoutesGridNextCell(dgCoreRoutes.CurrentCell);
       e.Handled = true;
       return true;
}
     else
           return base.ProcessCmdKey(ref msg, keyData);
    }

我返回 false 并将焦点设置到下一个控件,现在它对我有用。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
   if(keyData == Keys.Tab && dgCoreRoutes.CurrentCell == dgCoreRoutes.Rows[dgCoreRoutes.Rows.Count - 1].Cells[(int)enGridColumns.Margin])
   {
     btnNext.Focus(); 
     return false;
   }
   else if (keyData == Keys.Tab && dgCoreRoutes.CurrentCell.ReadOnly)
   {
     dgCoreRoutes.CurrentCell = GetCoreRoutesGridNextCell(dgCoreRoutes.CurrentCell);
     return true;
   }
   else
      return base.ProcessCmdKey(ref msg, keyData);
}