Winform中的dataGridView的某一个单元格添加下拉框(comboBox)

         最近一个需求,需要实现在dataGridView的单元格中放入下拉框进行选择,即放入comboBox控件,整体的思路很简单,comboBox通过代码进行初始化。在点击某个单元格的时候,触发单元格的事件,然后显示下拉框,当选择了数据之后,赢藏comboBox,并将选择的数据绑定到单元格对应的位置即可。

        首先建立一个Winform程序,拖入dataGridView控件。建立窗口的Load事件,编写一个dataGridView数据初始化方法和一个comboBox初始化的方法,在窗口Load事件中加载这两个方法。

		private void InitComboBox()
		{
			comboBox = new ComboBox();
			this.comboBox.Items.Add("通过");
			this.comboBox.Items.Add("未通过");
			this.comboBox.Leave += new EventHandler(ComboBox_Leave);
			this.comboBox.SelectedIndexChanged += new EventHandler(ComboBox_TextChanged);
			this.comboBox.Visible = false;
			this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

			this.dataGridView1.Controls.Add(this.comboBox);
		}
        private void ShowData()
		{
			this.dataGridView1.RowCount = 4;
			for(int i = 0;i < 4;i++)
			{
				this.dataGridView1.Rows[i].Cells["Column1"].Value = i;
				this.dataGridView1.Rows[i].Cells["Column2"].Value = i+1;
				this.dataGridView1.Rows[i].Cells["Column3"].Value = i+2;
				this.dataGridView1.Rows[i].Cells["Column4"].Value = "";
			}
		}

        此时数据等已经准备好,接下来是进行点击单元格显示comboBox的方法。

        在comboBox的初始化中需要添加comboBox的事件,comboBox_TextChanged事件。

 		private void ComboBox_TextChanged(object sender, EventArgs e)
		{
			this.dataGridView1.CurrentCell.Value = ((ComboBox)sender).Text;

			this.comboBox.Visible = false;
		}

       再编写dataGridView的CurrentCellChanged事件:

		private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
		{
			try
			{
				if (this.dataGridView1.CurrentCell.ColumnIndex == 3)
				{
					Rectangle rectangle = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false);

					string value = dataGridView1.CurrentCell.Value.ToString();
					this.comboBox.Text = value;
					this.comboBox.Left = rectangle.Left;
					this.comboBox.Top = rectangle.Top;
					this.comboBox.Width = rectangle.Width;
					this.comboBox.Height = rectangle.Height;
					this.comboBox.Visible = true;
				}
				else
				{
					this.comboBox.Visible = false;
				}
			}
			catch(Exception ex)
			{
				return;
			}
			
		}

        由于还需要在正常加载时不显示下拉框,以及选择完毕之后,隐藏掉下拉框,因此还需要Leave事件以及TextChanged事件:

		private void ComboBox_Leave(object sender,EventArgs e)
		{
			this.comboBox.Visible = false;
		}

		private void ComboBox_TextChanged(object sender, EventArgs e)
		{
			this.dataGridView1.CurrentCell.Value = ((ComboBox)sender).Text;

			this.comboBox.Visible = false;
		}

        源码已上传,需要的没有积分的可以联系我的邮箱。

        资源链接:https://download.csdn.net/download/qq_41061437/12046464

发布了165 篇原创文章 · 获赞 41 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41061437/article/details/103310219