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." });//此處需要判斷,根據對應行號,添加對應下拉列表,在此不再贅述 } }
