1. 程式人生 > >Winform中DataGridView網格添加ComBoBox

Winform中DataGridView網格添加ComBoBox

splay tar eight getc item winform lse ren control

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