Datagridview上的ComboBoxColumn中的“SelectedIndexChanged”事件

时间:2010-08-04 13:19:16

标签: c# .net winforms datagridview

我想在DataGridViewComboBoxColumn上处理此事件“SelectedIndexChanged”, 我将它设置在gridview的“EditingControlShowing”事件中。

问题: 首次尝试从组合框中选择一个项目时,不会触发“SelectedIndexChanged”事件,但是在第二次选择该项目后,该事件被触发并且一切正常!

以下是代码:

private void dgvRequest_EditingControlShowing(object sender,
     DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox combo = e.Control as ComboBox;

    if (combo != null)
    {
        if (dgvRequest.CurrentCell.ColumnIndex == col_ConfirmCmb.Index)
        {
            combo.SelectedIndexChanged -= combo_ConfirmSelectionChange;
            combo.SelectedIndexChanged += combo_ConfirmSelectionChange;

            return;
        }
    }
}


void combo_ConfirmSelectionChange(object sender, EventArgs e)
{
    if (dgvRequest.CurrentCell.ColumnIndex != col_ConfirmCmb.Index) return;

    ComboBox combo = sender as ComboBox;
    if (combo == null) return;

    MessageBox.Show(combo.SelectedText);// returns Null for the first time
}

1 个答案:

答案 0 :(得分:5)

事情变得复杂,因为他们通过对所有行只有一个编辑控件来优化DataGridView。以下是我处理类似情况的方法:

首先将委托连接到EditControlShowing事件:

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

然后在处理程序中,连接到EditControl的SelectedValueChanged事件:

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;

    }
}