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

Posted

技术标签:

【中文标题】如何验证 DataGridView 中单元格编辑控件的输入?【英文标题】:How can I validate input to the edit control of a cell in a DataGridView? 【发布时间】:2011-02-08 17:10:43 【问题描述】:

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

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

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

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

【问题讨论】:

【参考方案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 中编辑控件时取消连接任何可能的事件,因为它们将为多个单元格重用相同的控件。

【讨论】:

我也这么认为,但似乎编辑控件的类型总是 DataGridViewTextBoxEditingControl??

以上是关于如何验证 DataGridView 中单元格编辑控件的输入?的主要内容,如果未能解决你的问题,请参考以下文章

Datagridview:如何在编辑模式下设置单元格?

C# 如何使datagridview中的单元格处于可编辑

如何使用辅助文本框编辑 datagridview 单元格?

在c#中编辑datagridview后如何更新我的数据库

如何比较两个datagridview行单元格的值?

DataGridView单元格编辑