首页 文章

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

提问于
浏览
0

看来,在DataGridView控件的单元格中捕获按键事件以便在键入时验证用户输入的唯一方法是使用DataGridView控件OnEditControlShowing事件,将方法挂钩到编辑控件(e.Control)按键事件并做一些验证 .

我的问题是我已经构建了一堆自定义DataGridView列类,它们有自己的自定义单元格类型 . 这些单元格有自己的自定义编辑控件(比如DateTimePickers和Numeric或Currency文本框 . )

我想对那些具有货币文本框数字作为其编辑控件但不是所有其他单元格类型的单元格进行一些数字验证 .

如何在DataGridView的“OnEditControlShowing”覆盖中确定特定编辑控件是否需要进行一些数字验证?

1 回答

  • 1

    如果我正确理解您的问题,您可以选择根据编辑控件的类型连接事件 . 如果是这样,这就是我要做的:

    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中编辑控件的任何可能的事件,因为他们将为多个单元重用相同的控件 .

相关问题