您的位置:首页 > 编程语言

DataGridView控件中加入下拉框的编程实现

2013-06-11 00:24 344 查看
以下是在网上看到的网友发的文章“VC++.NET2005中DataGridView控件中加入下拉框的编程实现”用C#作了
修改的后的方法如下:



VS2005中新增加了数据浏览控件DataGridView,虽然我们可以通过其DataGridViewComboBoxColumn方法在DataGridView中添加下拉框列,但随之而来得问题是一整列的下拉框,很不美观,并且还要编程为其绑定数据,不符合.NET的尽量少干涉的原则。我最近通过对其Form控件的事件的简单编程实现了VS2005中DataGridView控件中加入下拉框的功能,写出来供大家参考:

在VS2005中创立一个C#语言的windows窗体应用程序,然后在Form1中添加一个DataGridView控件,这时系统会提示你为DataGridView控件绑定数据。完成以上工作后,在Form1上添加一个comboBox控件comboBox1

如图:



然后,用鼠标在Form1窗体上双击,进入 窗体Form1_Load事件代码编写处,如下所示:
private void Form1_Load(object sender, EventArgs e)

{

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.dgvStu.CurrentCell == null)

{

this.cobgv.Visible = false;

this.cobgv.Width = 0;

}

else

{

if (this.dgvStu.CurrentCell.ColumnIndex == 2)//下拉框所放置的列

{

this.cobgv.Visible = false;

this.cobgv.Width = 0;

this.cobgv.Left = this.dgvStu.GetCellDisplayRectangle(this.dgvStu.CurrentCell.ColumnIndex, this.dgvStu.CurrentCell.RowIndex, true).Left;

this.cobgv.Top = this.dgvStu.GetCellDisplayRectangle(this.dgvStu.CurrentCell.ColumnIndex, this.dgvStu.CurrentCell.RowIndex, true).Top;

this.cobgv.Width = this.dgvStu.GetCellDisplayRectangle(this.dgvStu.CurrentCell.ColumnIndex, this.dgvStu.CurrentCell.RowIndex, true).Width;

string ffff = Convert.ToString(this.dgvStu.CurrentCell.Value);

this.cobgv.Text = ffff;

this.cobgv.Visible = true;

}

else

{

this.cobgv.Visible = false;

this.cobgv.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事件,加入以下代码:

dataGridView1.CurrentCell.Value = ((System.Windows.Forms.ComboBox)sender).SelectedItem.ToString();

然后进入到comboBox1的KeyPress事件,加入以下代码:

this.comboBox1.Visible = false;

this.comboBox1.Width = 0;

comboBox1的KeyPress事件加入的代码主要解决编辑下拉框所在单元的数据时,如果不选用下拉框提供的

选项,而自己输入的问题。

以上就完成了下拉框的加入,我觉得这种方法比较简单,既不用重写控件,又利用了.NET提供的简单、便捷的设计方法,可以一用。在具体使用中可根据需要随便加入几个下拉框。以下几张图可见效果:

运行开始:



鼠标点击到下拉框单元:



开始在下拉框中选择:



选择完,鼠标离开下拉框单元后:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: