美文网首页
C#DataGridView与ComboBox实现下拉框选择

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

作者: 堆石成山 | 来源:发表于2020-08-19 17:54 被阅读0次

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

相关文章

网友评论

      本文标题:C#DataGridView与ComboBox实现下拉框选择

      本文链接:https://www.haomeiwen.com/subject/pirdjktx.html