Tab键到DataGridView中的下一个单元格

时间:2012-08-16 14:04:28

标签: c# datagridview

我有一个DataGridView,其中包含许多将其ReadOnly属性设置为True的单元格。

当用户使用tab键选中单元格时,如果ReadOnly属性为true,我想将焦点移动到下一个单元格。我的代码如下:

    private void filterGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        if (!filterGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly)
        {
            EditCell(sender, e);                
        }
        else
        {
            //Move to the next cell
            filterGrid.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Selected = true;
        }            
    }

但是,当我运行上面的代码时,我收到以下错误:

操作无效,因为它导致对SetCurrentCellAddressCore函数的可重入调用。

我正在使用C#4.0

提前致谢。

3 个答案:

答案 0 :(得分:3)

我使用派生的DataGridView来做这样的事情,这只会影响Tab键,所以用户仍然可以点击readonly单元格来复制粘贴它等等。

using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    class MyDGV : DataGridView
    {
        public bool SelectNextCell()
        {
            int row = CurrentCell.RowIndex;
            int column = CurrentCell.ColumnIndex;
            DataGridViewCell startingCell = CurrentCell;

            do
            {
                column++;
                if (column == Columns.Count)
                {
                    column = 0;
                    row++;
                }
                if (row == Rows.Count)
                    row = 0;
            } while (this[column, row].ReadOnly == true && this[column, row] != startingCell);

            if (this[column, row] == startingCell)
                return false;
            CurrentCell = this[column, row];
            return true;
        }

        protected override bool ProcessDataGridViewKey(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
                return SelectNextCell();
            return base.ProcessDataGridViewKey(e);
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if ((keyData & Keys.KeyCode) == Keys.Tab)
                return SelectNextCell();
            return base.ProcessDialogKey(keyData);
        } 
    }
}

答案 1 :(得分:0)

其中一个建议应该有效

使用

 else
        {
            filterGrid.ClearSelection();
            filterGrid.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Selected = true;
        }

Otherwise one other method is suggested here along with the reason
这也意味着同样的问题: - InvalidOperationException - When ending editing a cell & moving to another cell

答案 2 :(得分:0)

您可以使用datagridview单元格输入事件并将只读单元格选项卡索引旁路到另一个单元格。这是我的例子: -

    private void dgVData_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        if (dgVData.CurrentRow.Cells[e.ColumnIndex].ReadOnly)
        {
            SendKeys.Send("{tab}");
        }
    }
相关问题