如何让DataGridView中DataGridViewComboBoxColumn可选可编辑

导读:本篇文章讲解 如何让DataGridView中DataGridViewComboBoxColumn可选可编辑,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在开发过程中使用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 = “”;
            } 
        }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/51907.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!