文章不错,转过来,方便以后使用。
针对数据浏览控件DataGridView增加下拉框,虽然我们可以通过其DataGridViewComboBoxColumn方法在DataGridView中添加下拉框列,但问题是一整列的下拉框,很不美观,并且还要编程为其绑定数据,不符合.NET的尽量少干涉的原则。我最近通过有这方面的需求,通过学习可以根据Form控件的事件的简单编程实现了DataGridView控件中加入下拉框的功能,分享出来供大家参考:
在窗体上拖入一个ComboBox控件:
在Form1窗体上双击,进入 窗体Form1_Load事件代码编写处:
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
this.DataGridView1.Controls.Add(this.comboBox1);
然后在dataGridView1的CurrentCellChanged事件中:
try
{
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
if (this.DataGridView1.CurrentCell.ColumnIndex == 1)
{
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
this.comboBox1.Left = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Left;
this.comboBox1.Top = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Top;
this.comboBox1.Width = this.DataGridView1.GetCellDisplayRectangle(this.DataGridView1.CurrentCell.ColumnIndex, this.DataGridView1.CurrentCell.RowIndex, true).Width;
string ffff = Convert.ToString(this.DataGridView1.CurrentCell.Value);
this.comboBox1.Text = ffff ;
this.comboBox1.Visible = true;
}
else
{
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
注意:ColumnIndex == 1的 1 是你希望把comboBox1放在那一列上使用,根据需要来调整,再是这里一定要用TRY.........Catch结构,不然当你使用时,鼠标单击到列标题时,就会出现异常
然后进入到dataGridView1的Scroll事件,加入如下代码:
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
然后进入到comboBox1的SelectionChangeCommitted事件加入如下代码:
ComboBox sendBOX = (ComboBox)sender;
dataGridView1.CurrentCell.Value = sendBOX.SelectedValue.ToString();
然后进入到comboBox1的KeyPress事件加入如下代码:
this.comboBox1.Visible = false;
this.comboBox1.Width = 0;
以上操作完成了DataGridView中添加下拉框的整体操作。
希望可以帮到各位