2015/02/06

C#.Net 新增 DataGridViewComboBoxColumn 內容與值

Code:
using System;
using System.Windows.Forms;

namespace Sample
{
    public partial class Form1 : Form
    {
        class Pic
        {
            private String _name;
            private String _index;


            public Pic(String name, String index)
            {
                this._name = name;
                this._index = index;
            }
            /*必定為public*/
            public String GetName { get { return this._name; } }
            public String GetIndex { get { return this._index; } }
        }

        public Form1()
        {
            InitializeComponent();

            //下拉式選單
            DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();

            //樣板
            DataGridViewComboBoxCell cmbCell = new DataGridViewComboBoxCell();
            
            //將格式加入樣板
            for (int index = 1; index <= 4; index++)
                cmbCell.Items.Add(new Pic("Pic" + index, index.ToString()));

            //設定顯示對應的值
            cmbCell.DisplayMember = "GetName";
            
            //設定值對應的值
            cmbCell.ValueMember = "GetIndex";

            //將樣板設定給下拉式選單
            cmb.CellTemplate = cmbCell;

            //新增下拉式選單至DataGridView
            dataGridView1.Columns.Add(cmb);
        }


    }
}


執行結果: