views:

473

answers:

1

I have a DataGridView and a handler for the EditingControlShowing event which is used to add or remove handlers for the keyUp event for some columns. The problem is sometimes a column which does not have an associated KeyUp handler actually fires the handler. It seems like the grid does not know which column is supposed to fire which handler.

Problem: When I type in column2 (not column1), the line which removes the KeyUp handler runs.. so far so good. But then the Control_KeyUp runs! Control_KeyUp is only for Column1.

Is there a way to find out if a column (or cell?) has handlers attached to it?

    private void  MyGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
  {
   string columnName = MyGrid.Columns[MyGrid.CurrentCell.ColumnIndex].Name;
   if (columnName == "column1")
        e.Control.KeyPress += new KeyPressEventHandler(Control_KeyUp);
    else
        e.Control.KeyPress -= new KeyPressEventHandler(Control_KeyUp);
    ......

    }
+1  A: 

Here's similar question you may find useful:

http://stackoverflow.com/questions/582625/editingcontrolshowing-events-firing-multiple-times

From MSDN:

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.

Hope some of this helps.

Mr. Brownstone
I read the MSDN article. The keyword was that for the same type of column, the same Editingconrol is used. So if the editing control already has a handler, it will fire for ANY column using that editing control. So removing the handler before adding a new one was the answer.
Tony_Henrich