如何让DataGridView中DataGridViewComboBoxColumn可选可编辑

在开发过程中使用DataGridView控件时,要求下拉框可以编辑,但是默认的下拉框好像只能选择已有的选项!只能另想办法!

设计思路:在双击combox类型的cell时,将一个textbox(默认为不显示)显示在当前cell的上方,并让其获得输入焦点,回车键后将输入的数据添加到Item中,并隐藏textbox,textbox数据清空,同时cell中显示输入的数据,这样即可模拟combox可编辑可选!当然需要做些必要的判断,比如textbox如何显示到指定位置,textbox的大小,textbox的刷新,item数据的重复添加问题!现将代码粘贴如下,以作笔记:

//鼠标双击事件:

private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //鼠标双击时添加textbox到指定位置并获取焦点回车后添加到Item,释放控件
          

            //是否为下拉框
            if (e.ColumnIndex == 2 || e.ColumnIndex == 4)
            {
                textBox1.Text = "";
                textBox1.Visible = true;

                DataGridViewComboBoxCell dd = (DataGridViewComboBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];


                //取得选中单元格的坐标在DataGridView中的坐标位置:
                int cellX = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).X;

                int cellY = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Y;
                //然后把在控件中的坐标转换到屏幕坐标
                dataGridView1.PointToScreen(new Point(cellX, cellY));


                textBox1.Location =  new Point(cellX, cellY);
                textBox1.Size = new System.Drawing.Size(dataGridView1[e.ColumnIndex, e.RowIndex].Size.Width - 20, dataGridView1[e.ColumnIndex, e.RowIndex].Size.Height);
                textBox1.Focus();
                textBox1.KeyPress += keyPressEvent;
            }
        }

 

   private void keyPressEvent(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)//判断回车键
            {
                //MessageBox.Show("ok");
                //当前选中的datagridviewcell
               int index =     dataGridView1.SelectedCells[0].ColumnIndex;

               DataGridViewComboBoxColumn dgvCC = (DataGridViewComboBoxColumn)dataGridView1.Columns[index];
               
               //判断避免重复添加
                if(!dgvCC.Items.Contains(textBox1.Text.ToString().Trim()) || textBox1.Text.Trim() != "")
                    dgvCC.Items.Add(textBox1.Text.Trim());

                dataGridView1.SelectedCells[0].Value = dgvCC.Items[dgvCC.Items.Count-1];

                textBox1.Visible = false;
                textBox1.Text = "";
            } 
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

破浪征程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值