【问题标题】:KeyPress event blocks KeyUp event in DataGridView .netKeyPress 事件阻止 DataGridView .net 中的 KeyUp 事件
【发布时间】:2012-05-09 11:38:14
【问题描述】:

我想在 DataGridView 中将 30 个完整的苹果分配给 10 个人。
DataGridView 位于将 KeyPreview 设置为 true 的表单中。人员的姓名显示在设置为只读的 DataGridViewTextBoxColumn(Column1) 中。然后将整数输入到空的 DataGridViewTextBoxColumn(Column2) 中。 当一个键被释放时,总和被计算/重新计算,如果 column2 的总和为 30,则启用表单 OK 按钮(else disabled)。

问题在于keyEvents。如果绑定 KeyPress 事件,则不会触发 KeyUp。

    // Bind events to DataGridViewCell
    private void m_DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control != null)
        {
            e.Control.KeyUp -= m_DataGridView_KeyUp;
            e.Control.KeyPress -= m_DataGridView_KeyPress;
            e.Control.KeyUp += m_DataGridView_KeyUp;
            e.Control.KeyPress += m_DataGridView_KeyPress;
        }
    }

    //Only accept numbers
    private void m_GridView_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

   // Sum the apples in column2
   private void m_DataGridView_KeyUp(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 1 && e.RowIndex > 0)
        {
            int count = 0;
            int parser = 0;

            foreach (DataGridViewRow item in this.m_DataGridView.Rows)
            {
                if (item.Cells[1].Value != null)
                {
                    int.TryParse(item.Cells[1].Value.ToString(), out parser);
                    count += parser;
                }
            }

            //make the ok button enabled
            m_buttonDividedApplen.Enabled = (count == 30);
        }
    }

这个故事问题变得越来越陌生。如果我切换单元格,则会触发 keyup 事件。有时 keyup 会触发一次。

【问题讨论】:

  • KeyUp 不总是执行,还是仅在您在按键时处理它时执行?
  • KeyUp 仅在未附加 KeyPress 时执行。

标签: .net winforms datagridview c#-3.0 keyboard-events


【解决方案1】:

每次编辑控件触发时,您都会将处理程序重新附加到同一事件,我相信这永远不会改变。

我认为,如果您单步执行代码,您会注意到 KeyPress 事件的触发与您编辑单元格的次数成正比。尝试先删除处理程序:

    e.Control.KeyUp -= m_DataGridView_KeyUp;
    e.Control.KeyPress -= m_DataGridView_KeyPress;

然后重新附加:

    e.Control.KeyUp += m_DataGridView_KeyUp;
    e.Control.KeyPress += m_DataGridView_KeyPress;

并查看 KeyUp 是否触发。

【讨论】:

  • 嗯,我也试过了。结果是完全一样的。重新附加处理程序不会改变结果。
  • 啊,很抱歉没有帮助。不过,您可能不应该像那样连续重新附加处理程序,因为您的 KeyPress 事件会无意中触发多次。
  • 另外,我不清楚您为什么启用主表单的 KeyPreview。在设计时将处理程序附加到数据网格而不处理表单级别的按键事件不是可以吗?
  • 根据很多帖子,必须启用 KeyPreview 才能在 DataGridView 中注册键,但根据我的测试,它没有任何区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多