按 T​​AB 键时绕过 DataGridView 中的只读单元格 [英] Bypass read only cells in DataGridView when pressing TAB key

查看:17
本文介绍了按 T​​AB 键时绕过 DataGridView 中的只读单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我一些代码,如何在按下 TAB 键时绕过 DatagridView 中的只读单元格?

Can anyone show me some code of how I could bypass read only cells in DatagridView when pressing TAB key?

推荐答案

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

Overriding the SelectionChanged event is the right approach. The property CurrentCell can be used to set the current cell. You want something like this:

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

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

You'll need to add a test for the current cell being read only and loop while the next cell is invisible or read only. You'll also need to check to make sure that you don't loop for ever if all cells are read only.

您还必须处理显示索引与基本索引不同的情况.

You'll have to cope with the case where the display index is different to the base index too.

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

To get this behaviour just when pressing Tab you'll need to add a KeyDown handler:

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

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

and put the first code in this new method.

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

You might want to check that the DataGridView has focus too.

这篇关于按 T​​AB 键时绕过 DataGridView 中的只读单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆