[英]DataGridView, how to capture a cell's KeyPress event C#
i want to do treatement for a cell in datagridview c#, this traitement is open a form when i press a cell. 我想在datagridview c#中为一个单元格进行处理,当我按下一个单元格时,这个特征会打开一个表单。
in C# there isn't an event (keypress) which allows me to add my treatment directly 在C#中,没有一个事件(按键),允许我直接添加治疗方法
After search on internet, I found the following solution 在互联网上搜索后,我发现以下解决方案
private void dGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress +=
new KeyPressEventHandler(Control_KeyPress);
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if ((Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.A.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.Z.ToString())) || (Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D0.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D9.ToString()) || (Strings.Asc(e.KeyChar) >= 97 && Strings.Asc(e.KeyChar) > 122)))
{
------
}
}
but it doesn't work. 但它不起作用。 in debug the code of the event dGridView_EditingControlShowing was executed but the code of Control_KeyPress function does not run 在调试事件的代码dGridView_EditingControlShowing被执行但是Control_KeyPress函数的代码没有运行
any ideas please 任何想法,请
You should set your Form
KeyPreview
proprety to true . 您应该将Form
KeyPreview
属性设置为true 。 And you should handle the key pressed event on the main form. 并且您应该处理主窗体上的按键事件。 That is because Control.KeyPress
event 那是因为Control.KeyPress
事件
Occurs when a key is pressed while the control has focus. 在控件具有焦点的情况下按下键时发生。 ( msdn ) ( msdn )
public Form()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Control_KeyPress);
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
//your code
}
Just to make the first answer simple. 只是为了使第一个答案简单。 1) Go to your form's properties 2) Set the 'KeyPreview' to 'True' 3) On your form's Key Press event: 1)转到表单的属性2)将“KeyPreview”设置为“True”3)在表单的Key Press事件中:
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
//your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.