How can I validate input to the edit control of a cell in a DataGridView?

筅森魡賤 提交于 2019-12-25 12:09:50

问题


It appears that the only way to capture the keypress events within a cell of a DataGridView control in order to validate user input as they type, is to use the DataGridView controls OnEditControlShowing event, hook up a method to the edit control's (e.Control) keypress event and do some validation.

My problem is that I've built a heap of custom DataGridView column classes, with their own custom cell types. These cells have their own custom edit controls (things like DateTimePickers and Numeric or Currency textboxes.)

I want to do some numeric validation for those cells that have Numeric of Currency Textboxes as their edit controls but not all the other cell types.

How can I determine, within the DataGridView's "OnEditControlShowing" override, whether or not a particular edit control needs some numeric validation?


回答1:


If I understand your question correctly, you want to choose to wire up an event based on the type of the editing control. If so, this is what I'd do:

    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);
        }
    }

I've learned from experience to unwire any possible events on editing controls in DataGridView's, since they will reuse the same control for multiple cells.



来源:https://stackoverflow.com/questions/2651105/how-can-i-validate-input-to-the-edit-control-of-a-cell-in-a-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!