Tab to the next cell in a DataGridView
我有一个带有多个单元格的DataGridView,这些单元格的ReadOnly属性设置为True。
当用户使用Tab键浏览单元格时,如果ReadOnly属性为true,我想将焦点移至下一个单元格。 我的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | 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
提前致谢。
我将派生的DataGridView用于此类内容,这只会影响Tab键,因此用户仍可以单击只读单元格将其复制粘贴等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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); } } } |
您可以使用datagridview单元格Enter事件,并将只读单元格选项卡索引绕过另一个单元格。 这是我的例子:
1 2 3 4 5 6 7 | private void dgVData_CellEnter(object sender, DataGridViewCellEventArgs e) { if (dgVData.CurrentRow.Cells[e.ColumnIndex].ReadOnly) { SendKeys.Send("{tab}"); } } |
两个建议之一应该起作用
采用
1 2 3 4 5 | else { filterGrid.ClearSelection(); filterGrid.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Selected = true; } |
否则,在此建议其他方法以及原因
同样,这意味着相同的问题:-
InvalidOperationException-结束编辑单元格并移动到另一个单元格时