Attaching events to an TextBox underlying for a DataGridView cell

后端 未结 3 728
傲寒
傲寒 2021-01-19 16:28

Is there any way to get underlying control for a DataGridView cell? I would like to attach normal texbox events to capture keystrokes and capture value changed.

So i

3条回答
  •  情话喂你
    2021-01-19 17:19

    Subscribe the DataGridView.EditingControlShowing event, then subscribe the TextBox event you need.


    Example with TextBox.KeyDown :

    void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var txtBox = e.Control as TextBox;
        if (txtBox != null)
        {
            // Remove an existing event-handler, if present, to avoid 
            // adding multiple handlers when the editing control is reused.
            txtBox.KeyDown -= new KeyEventHandler(underlyingTextBox_KeyDown);
    
            // Add the event handler. 
            txtBox.KeyDown += new KeyEventHandler(underlyingTextBox_KeyDown);
        }
    }
    
    void underlyingTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        // ...
    }
    

    EDIT:

    Now the code is more correct, because it follows the suggestion given on MSDN:

    The DataGridView control hosts one editing control at a time, and reuses the editing control whenever the cell type does not change between edits. When attaching event-handlers to the editing control, you must therefore take precautions to avoid attaching the same handler multiple times. To avoid this problem, remove the handler from the event before you attach the handler to the event. This will prevent duplication if the handler is already attached to the event, but will have no effect otherwise. For more information, see the example code in the DataGridViewComboBoxEditingControl class overview.

    EDIT 2:

    As per comment:

    TextChanged event is called before EditingControlShowing, and then again after it.

    You can distinguish between the two calls using this trick:

    void txtBox_TextChanged(object sender, EventArgs e)
    {
        var txtBox = (TextBox)sender;
        if (txtBox.Focused)
        {
            // second call (after EditingControlShowing) the TextBox is focused
        }
        else
        {
            // first call (before EditingControlShowing) the TextBox is not focused
        }
    }
    

提交回复
热议问题