繁体   English   中英

Datagridview上ComboBoxColumn中的“ SelectedIndexChanged”事件

[英]“SelectedIndexChanged” event in ComboBoxColumn on Datagridview

我想在DataGridViewComboBoxColumn上处理“ SelectedIndexChanged”事件,并在gridview的“ EditingControlShowing”事件上进行设置。

问题:第一次尝试从comboBox中选择一个项目时不会触发“ 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
}

事情变得复杂,因为它们通过仅对所有行使用一个编辑控件来优化了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;

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM