DataGridView中下拉框的实现

文章不错,转过来,方便以后使用。

针对数据浏览控件DataGridView增加下拉框,虽然我们可以通过其DataGridViewComboBoxColumn方法在DataGridView中添加下拉框列,但问题是一整列的下拉框,很不美观,并且还要编程为其绑定数据,不符合.NET的尽量少干涉的原则。我最近通过有这方面的需求,通过学习可以根据Form控件的事件的简单编程实现了DataGridView控件中加入下拉框的功能,分享出来供大家参考:
       在窗体上拖入一个ComboBox控件:

    在Form1窗体上双击,进入 窗体Form1_Load事件代码编写处:

           this.comboBox1.Visible = false;
            this.comboBox1.Width = 0;
            this.DataGridView1.Controls.Add(this.comboBox1);

 然后在dataGridView1的CurrentCellChanged事件中:

try
            {               
                this.comboBox1.Visible = false;
                this.comboBox1.Width = 0;
                if (this.DataGridView1.CurrentCell.ColumnIndex == 1)
                {
                    this.comboBox1.Visible = false;
                    this.comboBox1.Width = 0;
                    this.comboBox1.Left = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Left;
                    this.comboBox1.Top = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Top;
                    this.comboBox1.Width = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Width;
                    string ffff = Convert.ToString(this.DataGridView1.CurrentCell.Value);
                    this.comboBox1.Text = ffff ;
                    this.comboBox1.Visible = true;
                }
                else
                {
                    this.comboBox1.Visible = false;
                    this.comboBox1.Width = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

注意:ColumnIndex == 1的 1 是你希望把comboBox1放在那一列上使用,根据需要来调整,再是这里一定要用TRY.........Catch结构,不然当你使用时,鼠标单击到列标题时,就会出现异常

 然后进入到dataGridView1的Scroll事件,加入如下代码:

           this.comboBox1.Visible = false;
              this.comboBox1.Width = 0;

然后进入到comboBox1的SelectionChangeCommitted事件加入如下代码:

            ComboBox sendBOX = (ComboBox)sender;
            dataGridView1.CurrentCell.Value = sendBOX.SelectedValue.ToString();

然后进入到comboBox1的KeyPress事件加入如下代码:

            this.comboBox1.Visible = false;
              this.comboBox1.Width = 0;

以上操作完成了DataGridView中添加下拉框的整体操作。

希望可以帮到各位

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值