开发者

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

开发者 https://www.devze.com 2022-12-26 20:47 出处:网络
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 OnEditControlShowi

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消