码迷,mamicode.com
首页 > Windows程序 > 详细

Winform中DataGridView网格添加ComBoBox

时间:2019-02-11 15:24:26      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:字体   ems   winform   init   loaddata   component   als   字段名   null   

在工作中遇到需要在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;
    }
  }

}

Winform中DataGridView网格添加ComBoBox

标签:字体   ems   winform   init   loaddata   component   als   字段名   null   

原文地址:https://www.cnblogs.com/lylongs/p/10361926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!