我有一个问题的处理索引更改的事件为一个comboBox驻留在一个dataGridView。我写了一个方法来处理comboBox的选择变化使用委托:
ComboBox.SelectedIndexChanged -= delegate { ComboBoxIndexChanged(); };
ComboBox.SelectedIndexChanged += delegate { ComboBoxIndexChanged(); };
或eventandler:
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
,但这两种方法都不像预期的那样工作。也就是说,当你点击你的选择在comboBox(包含在dataGridView),它需要多次点击导致我的ComboBoxIndexChanged();方法的正确运作,如果它决定运作。什么是最好的方法来克服/去指定一个事件indexedChange的组合框在一个dataGridView?
我目前在上下文中使用的代码如下:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
if (this.dataGridView.CurrentCell.ColumnIndex == (int)Column.Col)
{
ComboBox comboBox = e.Control as ComboBox;
if (comboBox != null)
{
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
}
}
return;
}
catch (Exception Ex)
{
Utils.ErrMsg(Ex.Message);
return;
}
}
和ComboBoxIndexChanged事件为:
private void ComboBoxIndexChanged(object sender, EventArgs e)
{
// Do some amazing stuff...
}
我在StackOverFlow上读过一个类似的线程,其中指出以这种方式处理comboBox更改事件存在问题,但我无法得到解决方案。这篇文章可以在这里找到:SelectedIndexChanged"Datagridview上的ComboBoxColumn中的事件。它说:
"事情变得复杂,因为他们优化了DataGridView只有一个编辑控件的所有行。下面是我处理类似情况的方法:
首先连接一个委托到editcontrolshow事件:
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;
}
}"
我遇到的这个问题是"VisSender"没有定义,因此事件"visblechanged"不能使用。
小伙子们的任何帮助,我总是非常感激。
听起来您希望在用户更改下拉框时立即提交更改,而不需要单击单元格。为了做到这一点,您需要在发生更改时强制提交(使用CommitEdit
, MSDN页面上也有一个示例)。将此添加到您的DataGridView
:
// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
然后你可以只是监听CellValueChanged
,避免不得不尝试和注册的ComboBoxValueChanged事件上的底层编辑控件