代码之家  ›  专栏  ›  技术社区  ›  Stuart Helwig

如何验证DataGridView中单元格的编辑控件的输入?

  •  0
  • Stuart Helwig  · 技术社区  · 16 年前

    看来,在DataGridView控件的单元格中捕获keypress事件以便在用户输入时验证用户输入,唯一的方法是使用DataGridView控件OneEditControlShowing事件,将方法连接到编辑控件(e.control)的keypress事件并进行一些验证。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Mashmagar    16 年前

    如果我正确地理解了您的问题,您希望根据 编辑控件的类型 . 如果是这样,我会这样做:

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //Remove any KeyPress events already attached
            e.Control.KeyPress -= new KeyPressEventHandler(FirstEditingControl_KeyPress);
            e.Control.KeyPress -= new KeyPressEventHandler(SecondEditingControl_KeyPress);
    
            //Choose event to wire based on control type
            if (e.Control is NumericTextBox)
            {
                e.Control.KeyPress += new KeyPressEventHandler(FirstEditingControl_KeyPress);
            } else if (e.Control is CurrencyTextBox)
            {
                e.Control.KeyPress += new KeyPressEventHandler(SecondEditingControl_KeyPress);
            }
        }
    

    我从经验中学到了在DataGridView中编辑控件时可能发生的任何事件,因为它们会对多个单元格重用同一个控件。

    推荐文章