【发布时间】:2016-10-30 01:53:37
【问题描述】:
我正在重新提出这个问题,因为我现在有一些代码可以解决我的问题(我删除了旧问题)。
基本上,当在编辑文本框单元格时按下回车键时,我希望它像 Tab 按下一样(当前行中的下一列而不是同一列中的下一列)。
我的问题是到目前为止我尝试过的大部分方法都不起作用,但是这是我目前尝试的解决方案。
此代码应该更改正在编辑/选择的单元格。
private void PreTranslateDGV_KeyPressEvent(object sender, KeyEventArgs e)
{
DataGridViewTextBoxEditingControl a = (DataGridViewTextBoxEditingControl) sender;
//a.PreviewKeyDown -= PreviewKeyDownEventHandler (dataGridView1_PreviewKeyDown)
MyDataGridView s = (MyDataGridView) a.EditingControlDataGridView;
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
int newRow;
int newColumn;
if (s.CurrentCell.ColumnIndex == s.ColumnCount - 1) // it's a last column, move to next row;
{
newRow = s.CurrentCell.RowIndex + 1;
newColumn = 0;
if (newRow == s.RowCount)
return; // ADD new row or RETURN (depends of your purposes..)
}
else // just change current column. row is same
{
newRow = s.CurrentCell.RowIndex;
newColumn = s.CurrentCell.ColumnIndex + 1;
}
s.CurrentCell = s.Rows[newRow].Cells[newColumn];
}
}
这是将上述事件添加到单元格文本框的代码
private void PreTranslateDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Control;
tb.KeyDown += new KeyEventHandler (PreTranslateDGV_KeyPressEvent);
}
其中大部分是我从 StackOverflow 中找到的代码,因为我一直试图让它工作一段时间。
如果有人知道如何从 datagridview 中正确获取“Enter”键,请在编辑单元格时提供帮助。
PS:我在 MSDN 论坛上阅读(丢失的链接)编辑文本框单元格时,当您按 Enter 时它会停止编辑。这可以解释为什么我上面的代码在 Enter 时不会触发,但它会触发其他所有内容。
我现在正试图通过覆盖 processcmdkey 来做到这一点
class MyDataGridView : KryptonDataGridView
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((keyData == Keys.Enter) && (this.EditingControl != null))
{
return false;
}
//for the rest of the keys, proceed as normal
return base.ProcessCmdKey(ref msg, keyData);
}
}
但无论我似乎返回什么,Enter 键都不会传递给 KeyPressEvent。
【问题讨论】:
标签: c# datagridview