C#DataGridView与ComboBox实现下拉框选择

1、ComboBox添加元素

comboBox1.Visible =false;
comboBox1.Items.Add("线性")
comboBox1.Items.Add("非线性")

2、dataGridView添加控件

dataGridView1.Controls.Add(comboBox1);

以上可放在_Load方法内。

3、当选中dataGridView1的指定列时显示comboBox控件,并调整控件的大小与dataGridView1的cell大小一致

private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentCell.ColumnIndex == 9)
                {
                    Rectangle rect = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false);
                    string sexValue = dataGridView1.CurrentCell.Value.ToString();                  
                    comboBox1.Left = rect.Left;
                    comboBox1.Top = rect.Top;
                    comboBox1.Width = rect.Width;
                    comboBox1.Height = rect.Height;
                    comboBox1.SelectedItem = dataGridView1.CurrentCell.Value;
                    comboBox1.Visible = true;
                }
                else
                {
                    comboBox1.Visible = false;
                }
            }
            catch
            {
            }
        }

4、 comboBox1选择改变时赋值给dataGridView1

if(dataGridView1.CurrentCell!=null)
          dataGridView1.CurrentCell.Value = comboBox1.SelectedItem.ToString();

看效果

效果.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。