关于datagridview控件的事件

时间:2011-02-26 07:12:35

标签: c# .net winforms datagridview

我开发了一个datagridview过滤应用程序。我使用了datagridview' s dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 过滤事件。 但我想在datagridview单元的按键事件上处理它。但我没有得到那种类型的活动。

  

应该发生datagridview事件   在每个按键..

那么有人可以告诉我应该将哪个事件用于datagridview吗?

请帮帮我... 感谢名单

1 个答案:

答案 0 :(得分:3)

当用户键入特定单元格时,DataGridView.KeyPress事件将。如果您希望在编辑单元格中的内容时每次按下某个键时收到通知,则有两个选项:

  1. 处理由编辑控件本身(您可以使用KeyPress事件访问)直接引发的EditingControlShowing事件。

    例如,您可以使用以下代码:

    public class Form1 : Form
    {
        public Form1()
        {
            // Add a handler for the EditingControlShowing event
            myDGV.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(myDGV_EditingControlShowing);
        }
    
        private void myDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            // Ensure that the editing control is a TextBox
            TextBox txt = e.Control as TextBox;
            if (txt != null)
            {
                // Remove an existing event handler, if present, to avoid adding
                // multiple handler when the editing control is reused
                txt.KeyPress -= new KeyPressEventHandler(txt_KeyPress);
    
                // Add a handler for the TextBox's KeyPress event
                txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
            }
        }
    
        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Write your validation code here
            // ...
    
            MessageBox.Show(e.KeyChar.ToString());
    
        }
    }
    
  2. 创建一个继承自标准DataGridView控件的自定义类,并覆盖其ProcessDialogKey method。此方法旨在处理每个关键事件,即使是那些 在编辑控件上发生。您可以处理该重写方法中的按键,或者引发您自己的事件,您可以附加一个单独的处理程序方法。