c# datagridview列形式为Combobox,每行下拉选项不一样
方法1:
/// <summary>
/// 首先给这个DataGridView加上EditingControlShowing事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvSelectFun_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dgv = sender as DataGridView;
判断相应的列
if (dgv.CurrentCell.GetType().Name == "DataGridViewComboBoxCell" && dgv.CurrentCell.RowIndex != -1)
{
DataGridViewComboBoxCell combox = dgv.CurrentCell as DataGridViewComboBoxCell;
combox.DataSource = FunsLib[dgv.CurrentCell.RowIndex].FuncSnALL;
//给这个DataGridViewComboBoxCell加上下拉事件
(e.Control as ComboBox).SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
/// <summary>
/// 组合框事件处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></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);
}
}
/// <summary>
/// 离开combox时,把事件删除
/// 这一步比较重要,如果不加,会导致selectedchanged事件一直触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void combox_Leave(object sender, EventArgs e)
{
ComboBox combox = sender as ComboBox;
//做完处理,须撤销动态事件
combox.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
}
方法2:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
//判断相应的列
if (dgv.CurrentCell.GetType().Name == "DataGridViewComboBoxCell" && dgv.CurrentCell.RowIndex != -1)
{
//此处绑定数据源,或者直接清除下拉列表,重新添加
DataGridViewComboBoxCell combox = dgv.CurrentCell as DataGridViewComboBoxCell;
combox.DataSource = FunsLib[i].FuncSnALL;//FunsLib:List<List<string>>
//combox.Items.Clear();
//combox.Items.AddRange(new string[] { "A1.", "A2." });//此处需要判断,根据对应行号,添加对应下拉列表,在此不再赘述
}
}