在工作中遇到需要在DataGridView网格中添加ComBoBox的需求.解决后记录
1 在窗体类中声明一个全局的变量ComBoBox,并在Form的Load事件中设置号ComBoBox的下拉选项
2 在DataGridView绑定完数据源之后,将ComBoBox添加到DataGridView中
3 编写DataGridView的CurrentCellChanged事件和ComBoBox的SelectedIndexChanged事件
完整代码如下:
public partial class Form1 : Form
{
ComboBox cmb = new ComboBox();
public Form1()
{
InitializeComponent();
this.dgv1.AutoGenerateColumns = false;
}
private void Form1_Load(object sender, EventArgs e)
{
LoadDataSource();
InitCmb();
this.dgv1.Controls.Add(cmb);
this.dgv1.CurrentCellChanged += new System.EventHandler(this.dgv1_CurrentCellChanged);
}
private void InitCmb()
{
this.cmb.Items.Add("新增");
this.cmb.Items.Add("删除");
this.cmb.Items.Add("修改类型");
this.cmb.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged);
}
private void cmb_SelectedIndexChanged(object sender, EventArgs e)
{
dgv1.CurrentCell.Value = cmb.Text;
}
private void LoadDataSource()
{
DataTable tb = new DataTable();
tb.Columns.Add("序号", typeof(Int32));
tb.Columns.Add("字段名");
tb.Columns.Add("操作");
DataRow dr = tb.NewRow();
dr["序号"] = 1;
dr["字段名"] = "Name";
dr["操作"] = "";
tb.Rows.Add(dr);
dr = tb.NewRow();
dr["序号"] = 2;
dr["字段名"] = "Gender";
dr["操作"] = "";
tb.Rows.Add(dr);
this.dgv1.DataSource = tb;
}
private void dgv1_CurrentCellChanged(object sender, EventArgs e)
{
if (dgv1.DataSource == null)
return;
DataTable tb = (DataTable)dgv1.DataSource;
DataGridViewCell currentCell = dgv1.CurrentCell;
if (currentCell != null && currentCell.RowIndex < tb.Rows.Count && currentCell.OwningColumn.Name == "C操作")
{
Rectangle rect = dgv1.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, true);
cmb.Text = currentCell.Value.ToString();
cmb.Size = rect.Size;//其实这里设置它的Size,只有width有效,如果要Height有效,需要重写ComBoBox控件,系统自带的ComBoBox空间的高度只能通过字体大小来自动适应
cmb.Top = rect.Top;
cmb.Left = rect.Left;
cmb.Visible = true;
}
else
{
cmb.Visible = false;
}
}
}
原文地址:https://www.cnblogs.com/lylongs/p/10361926.html