问题:DataGridView绑定数据源之后,有一列需要用下拉框DataGridViewComboBoxCell显示,但是在措置惩罚惩罚DataGridViewComboBoxCell的下拉事件有些麻烦,它不像ComBox有SelectedIndexChanged,困扰我很久,结合网上的一些要领,再加上本身的一些窜改,终于完全可以解决这个问题了。下面是我的代码,有详细注释。
一、
/// <summary>
/// 首先给这个DataGridView加上EditingControlShowing事件
/// </summary>
/// <param></param>
/// <param></param>
public void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dgv = sender as DataGridView;
//判断相应的列
if (dgv.CurrentCell.GetType().Name == "DataGridViewComboBoxCell" && dgv.CurrentCell.RowIndex != -1)
{
//给这个DataGridViewComboBoxCell加上下拉事件
(e.Control as ComboBox).SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
二、
/// <summary>
/// 组合框事件措置惩罚惩罚
/// </summary>
/// <param></param>
/// <param></param>
public void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox combox=sender as ComboBox;
//这里对照重要
combox.Leave+=new EventHandler(combox_Leave);
try
{
//在这里就可以做值是否转变判断
if (combox.SelectedItem != null)
{
}
Thread.Sleep(100);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
三、(这一步对照重要,如果不加,会导致selectedchanged事件一直触发)
/// <summary>
/// 分开combox时,把事件删除
/// </summary>
/// <param></param>
/// <param></param>
public void combox_Leave(object sender, EventArgs e)
{
ComboBox combox = sender as ComboBox;
//做完措置惩罚惩罚,须勾销动态事件
combox.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
}
总结:网上的要领一般都是在第二步的时候把
//做完措置惩罚惩罚,,须勾销动态事件
combox.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);