c# datagridview列形式为Combobox,每行下拉选项不一样

c# datagridview列形式为Combobox,每行下拉选项不一样

方法1:

 /// 
        /// 首先给这个DataGridView加上EditingControlShowing事件
        /// 
        /// 
        /// 
        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);
            }
        }

        /// 
        /// 组合框事件处理
        /// 
        /// 
        /// 
        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);
            }
        }

        /// 
        /// 离开combox时,把事件删除
        /// 这一步比较重要,如果不加,会导致selectedchanged事件一直触发
        /// 
        /// 
        /// 
        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>

            //combox.Items.Clear();
            //combox.Items.AddRange(new string[] { "A1.", "A2." });//此处需要判断,根据对应行号,添加对应下拉列表,在此不再赘述
        }
    }

你可能感兴趣的:(C#,datagridview,下拉框数据源)