1. 程式人生 > >在Winform視窗中為DataGridview單元格新增ComboBox

在Winform視窗中為DataGridview單元格新增ComboBox

1. 前言

在進行軟體開發時遇到需要在DataGridView控制元件的單元格中新增ComboBox的需求,經過網路部落格等方式查詢解決辦法,最後成功解決,在本文中予以記錄。

2. 實現

首先這裡需要一個動態的ComboBox
private ComboBox Score_ComboBox = new ComboBox();
在窗體初始中設定它的基本屬性和將其新增到DataGridView,在這裡我設定了離開選中索引改變的響應函式
 for (int i = 0; i <= 10; i++)
            {
                this.Score_ComboBox.Items.Add(i.ToString());
            }
            this.Score_ComboBox.Text = "0";
            this.Score_ComboBox.Leave += new EventHandler(comboBox50_TextChanged);
            this.Score_ComboBox.SelectedIndexChanged += new EventHandler(comboBox50_TextChanged);
            this.Score_ComboBox.Visible = false;
            this.Score_ComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

            // 將下拉列表框加入到DataGridView控制元件中
            this.dataGridView1.Controls.Add(this.Score_ComboBox);
響應函式:
 private void comboBox50_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ((ComboBox)sender).Text = cType.cint(((ComboBox)sender).Text).ToString();
                int row_index = this.dataGridView1.CurrentCell.RowIndex;
                DataTable data = (this.dataGridView1.DataSource as DataTable);
                data.Rows[row_index][2] = ((ComboBox)sender).Text;
                if (cType.cint(((ComboBox)sender).Text) > 10)
                {
                    MessageBox.Show("請輸入合法數值!");
                    ((ComboBox)sender).Text = "";
                }
                this.Score_ComboBox.Visible = false;
            }
            catch (Exception ex)
            {
            }
        }
為DataGridView控制元件新增單元格變化響應
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentCell.ColumnIndex == 2 && this.dataGridView1.CurrentCell.RowIndex <this.row_num)
                {
                    Rectangle rect = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false);
                    string Value = dataGridView1.CurrentCell.Value.ToString();
                    this.Score_ComboBox.Text = Value;
                    this.Score_ComboBox.Left = rect.Left;
                    this.Score_ComboBox.Top = rect.Top;
                    this.Score_ComboBox.Width = rect.Width;
                    this.Score_ComboBox.Height = rect.Height;
                    this.Score_ComboBox.Visible = true;
                }
                else
                {
                    this.Score_ComboBox.Visible = false;
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
至此,就已經準備完成,