C# 在DataGridView中将焦点设置为不同的列
DataGridView控件中的列0为只读。如果用户用鼠标选择列0或按上一行最后一列的tab键,我希望焦点移到列1。我在CellEnter事件中尝试了以下代码,但它导致异常“操作无效,因为它导致对CurrentCellAddressCore函数的可重入调用”。第1列命名为“patternsTerminator” 我理解为什么会发生异常。当焦点移到第1列时,会再次调用CellCenter事件,异常会阻止对CellCenter事件的递归调用 我尝试了以下解决方法,但它忽略了tab键。当我在第0列中单击时,会调用SendKeys,但光标停留在第0列中C# 在DataGridView中将焦点设置为不同的列,c#,winforms,datagridview,C#,Winforms,Datagridview,DataGridView控件中的列0为只读。如果用户用鼠标选择列0或按上一行最后一列的tab键,我希望焦点移到列1。我在CellEnter事件中尝试了以下代码,但它导致异常“操作无效,因为它导致对CurrentCellAddressCore函数的可重入调用”。第1列命名为“patternsTerminator” 我理解为什么会发生异常。当焦点移到第1列时,会再次调用CellCenter事件,异常会阻止对CellCenter事件的递归调用 我尝试了以下解决方法,但它忽略了tab键。当我在第0列中单
if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
SendKeys.Send("{TAB}");
我在这个网站和其他网站上读过很多帖子,但都没法用。如有任何建议,将不胜感激
谢谢大家! 我绕过了异常,但焦点不正确-对我来说,它想用以下代码跳过第2列。我没时间了。如果你拿不到,我会很快跟进
private void DgNew_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
this.BeginInvoke(new MethodInvoker(() =>
{
moveCellTo(dgNew, e.RowIndex, 1);
}));
}
}
private void moveCellTo(DataGridView dgCurrent, int rowIndex, int columnIndex)
{
dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnIndex];
}
我从这篇文章中得到了这个想法:除了Jared的答案之外,我还测试了以下代码,它可以正常工作。这与Jared的答案之间的唯一区别是columnIndex是通过其名称而不是索引值来引用的。再次感谢你,杰瑞德
try
{
// Display the pattern number in column 0
this.dataGridView_patterns.Rows[currentRow].Cells["patternNumber"].Value = currentRow + 1;
// Move the current cell focus to column 1 (Terminator pattern) on current row
if (e.ColumnIndex == 0)
{
this.BeginInvoke(new MethodInvoker(() =>
{
moveCellTo(dataGridView_patterns, e.RowIndex, "patternsTer");
}));
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, errCaption, button, icon);
}
}
private void moveCellTo(DataGridView dgCurrent, int rowIndex, string columnName)
{
dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnName];
}
这真的是你想要的。。。谢谢,阿奎尔基,我在打开这篇文章之前读过这篇文章,但没有得到任何有用的建议。我甚至在这里发布,它似乎忽略了传递给SendKeys()的制表符。这个问题有很多不同的答案。你认为我应该专注于哪一个?太棒了,杰瑞德。我只需将dgNew更改为我控件的名称,它就可以完美地工作。实际上,当第一列(columnIndex=0)具有焦点时,我希望光标转到第二列(columnIndex=1)。我不确定你说的第二列是否就是这个意思,因为columnIndex是基于0的。非常感谢您的解决方案!
try
{
// Display the pattern number in column 0
this.dataGridView_patterns.Rows[currentRow].Cells["patternNumber"].Value = currentRow + 1;
// Move the current cell focus to column 1 (Terminator pattern) on current row
if (e.ColumnIndex == 0)
{
this.BeginInvoke(new MethodInvoker(() =>
{
moveCellTo(dataGridView_patterns, e.RowIndex, "patternsTer");
}));
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, errCaption, button, icon);
}
}
private void moveCellTo(DataGridView dgCurrent, int rowIndex, string columnName)
{
dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnName];
}