我使用代码datagrid1.controls.add(frmnew)
向datagridview添加了一个表单。问题是,该形式的控件的按键事件不会触发。请给我一个解决方案。
答案 0 :(得分:0)
如果您使用的是Windows窗体:
检查.Designer.cs文件中是否有事件处理程序。
事件处理程序如下所示:
this.datagrid1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.datagrid1_KeyPress);
答案 1 :(得分:0)
如果要捕获datagridview控件内的keypress事件,则必须连接事件 EditingControlShowing 。以下是捕获按键事件并仅允许将数字数据输入datagridview单元格的示例。
/// <summary>
/// Occurs when a control for editing a cell is showing
/// </summary>
/// <remarks>Capture key press to handle key entry in datagridview</remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgDCAL_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
dgDCAL.EditingControl.KeyPress -= EditingControl_KeyPress;
dgDCAL.EditingControl.KeyPress += EditingControl_KeyPress;
}
/// <summary>
/// Handle datagridview cell keypress event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow 0-9, backspace, period and return key
if (!Char.IsNumber(e.KeyChar) &&
(int)e.KeyChar != 8 &&
(int)e.KeyChar != 46 &&
(int)e.KeyChar != 13) e.Handled = true;
}