按TAB键时,绕过DataGridView中的只读单元格

Cor*_*nel 8 c# datagridview

任何人都可以向我展示一些代码,告诉我如何在按TAB键时绕过DatagridView中的只读单元格?

小智 13

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
   if (dataGridView1.CurrentRow.Cells[e.ColumnIndex].ReadOnly)
    {
        SendKeys.Send("{tab}");
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*isF 5

覆盖SelectionChanged事件是正确的方法.CurrentCell属性可用于设置当前单元格.你想要这样的东西:

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
    DataGridViewCell currentCell = dataGridView.CurrentCell;
    if (currentCell != null)
    {
        int nextRow = currentCell.RowIndex;
        int nextCol = currentCell.ColumnIndex + 1;
        if (nextCol == dataGridView.ColumnCount)
        {
            nextCol = 0;
            nextRow++;
        }
        if (nextRow == dataGridView.RowCount)
        {
            nextRow = 0;
        }
        DataGridViewCell nextCell = dataGridView.Rows[nextRow].Cells[nextCol];
        if (nextCell != null && nextCell.Visible)
        {
            dataGridView.CurrentCell = nextCell;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要为当前正在读取的单元格添加测试并循环,而下一个单元格不可见或只读.如果所有单元格都是只读的,您还需要检查以确保不会循环.

您将不得不应对显示索引与基本索引不同的情况.

要在按Tab键时获得此行为,您需要添加KeyDown处理程序:

private void AlbumChecker_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        SelectNextEditableCell(DataGridView dataGridView);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将第一个代码放在这个新方法中.

您可能想要检查DataGridView是否也具有焦点.

  • 当单元格处于编辑模式时,最后一个将无法工作:( (2认同)