问题
I'm creating a custom editing control for my DataGridView in my winforms application, and I'd like to raise an event when the user hits the enter key, but before the datagridview scrolls to the next row. I don't really care if the event is raised by the cell, or the editing control as I can propagate the event as needed. So far I've tried to override both the OnKeyDown and OnKeyUp methods of the DataGridViewTextBoxCell class which I'm inheriting from and neither of these methods seems to be called if the cell is in editing mode. I also tried Handling the KeyDown event of the TextBox control in my editing control. This one does get called, but it happens only after the DataGridView has already scrolled to the next row (I need to raise the event before the scroll). Any ideas? Thanks in advance for the help.
回答1:
if you are creating a custom DataGridView
control then you can override ProcessCmdKey
event in DataGridView
class.
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
int ColumnIndex = dataGridView1.CurrentCell.ColumnIndex;
int RowIndex = dataGridView1.CurrentCell.RowIndex;
if (keyData == Keys.Return || keyData == Keys.Enter)
{
if (ColumnIndex == dataGridView1.Columns.Count - 1)
{
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1.Rows[RowIndex].Cells[0];
}
else
dataGridView1.CurrentCell = dataGridView1.Rows[RowIndex].Cells[RowIndex];
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
}
来源:https://stackoverflow.com/questions/24699521/winforms-datagridview-custom-edit-control-cell