“SelectedIndexChanged” event in ComboBoxColumn on Datagridview

后端 未结 1 1817
独厮守ぢ
独厮守ぢ 2021-01-15 15:41

I want to handle this event \"SelectedIndexChanged\" on a DataGridViewComboBoxColumn, and I set it on \"EditingControlShowing\" event of the gridview.

The problem :

相关标签:
1条回答
  • 2021-01-15 16:31

    Things get complicated since they optimized the DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation:

    First hook up a delegate to the EditControlShowing event:

    myGrid.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(
                                        Grid_EditingControlShowing);
    ...
    

    Then in the handler, hook up to the EditControl's SelectedValueChanged event:

    void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        ComboBox combo = e.Control as ComboBox;
        if (combo != null)
        {
            // the event to handle combo changes
            EventHandler comboDelegate = new EventHandler(
                (cbSender, args) =>
                {
                    DoSomeStuff();
                });
    
            // register the event with the editing control
            combo.SelectedValueChanged += comboDelegate;
    
            // since we don't want to add this event multiple times, when the 
            // editing control is hidden, we must remove the handler we added.
            EventHandler visibilityDelegate = null;
            visibilityDelegate = new EventHandler(
                (visSender, args) =>
                {
                    // remove the handlers when the editing control is
                    // no longer visible.
                    if ((visSender as Control).Visible == false)
                    {
                        combo.SelectedValueChanged -= comboDelegate;
                        visSender.VisibleChanged -= visibilityDelegate;
                    }
                });
    
            (sender as DataGridView).EditingControl.VisibleChanged += 
               visibilityDelegate;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题