选项卡索引在数据网格视图行中循环,而不是以窗体形式移动到下一个控件,c#

时间:2015-05-11 07:39:32

标签: c# winforms datagridview tabindex

如果tab index在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;
}

2 个答案:

答案 0 :(得分:0)

就投资而言,当您在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);
    }

答案 1 :(得分:0)

我返回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);
}