【问题标题】:About datagridview control's event关于datagridview控件的事件
【发布时间】:2011-02-26 07:12:34
【问题描述】:

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

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

那么谁能告诉我应该为 datagridview 使用哪个事件?

请帮帮我... 谢谢

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    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。此方法旨在处理每个关键事件,即使是那些
      发生在编辑控件上。您可以在该重写方法中处理按键,也可以引发您自己的事件,您可以将单独的处理程序方法附加到该事件。

    【讨论】:

    • 但我也想要行索引和列索引。那么我怎样才能得到上面代码中的行索引和列索引呢?
    • @priyanka:最简单的方法是使用DataGridView.CurrentCell property。它将返回当前选择的cell,进而公开ColumnIndexRowIndex 属性。
    • 如何给datagridview当前单元格设置e.keychar值?因为当我在我的应用程序中使用上述事件时,它会将当前单元格显示为空值,因此我无法执行其他操作。
    • @priyanka:当你拿到那个单元格时。您只需要在自定义按键事件中设置e.Handled=false
    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多