gpt4 book ai didi

c# - Datagridview 上 ComboBoxColumn 中的 "SelectedIndexChanged"事件

转载 作者:行者123 更新时间:2023-12-02 17:54:45 26 4
gpt4 key购买 nike

我想在 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
}

最佳答案

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

首先将委托(delegate)连接到 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;

}
}

关于c# - Datagridview 上 ComboBoxColumn 中的 "SelectedIndexChanged"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com