如何让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 = "";
            } 
        }

你可能感兴趣的:(C#,C#)