先準備好類別欄位資料
public enum Sex { Man, Woman }; public class Member { public int ID { get; set; } public string Name { get; set; } public Sex Sex { get; set; } }
然後在用戶端裡綁定控制項
BindingList<Member> _members = null; BindingSource _memberSource = new BindingSource(); private void Form1_Load(object sender, EventArgs e) { this._members = new BindingList<Member>() { new Member() { ID = 2, Name = "GY1", Sex = Sex.Man,IsJoin=true }, new Member() { ID = 2, Name = "GY2", Sex = Sex.Man,IsJoin=false }, new Member() { ID = 3, Name = "GY3", Sex = Sex.Woman,IsJoin=true }, new Member() { ID = 4, Name = "GY4", Sex = Sex.Man ,IsJoin=false} }; this._memberSource.DataSource = this._members; this.bindingNavigator1.BindingSource = this._memberSource; this.dataGridView1.DataSource = this._memberSource; this.dataGridView1.AutoGenerateColumns = true;//開始重繪欄位 }
執行結果就會像下面那張圖,dataGridView1在綁定時不會幫我們建立DataGridViewComboBoxColumn欄位
我們可以利用AutoGenerateColumns 屬性來停止自動建立欄位,用我們自己想要呈現的DataGridViewColumn樣式
private void Form1_Load(object sender, EventArgs e) { this._members = new BindingList<Member>() { new Member() { ID = 2, Name = "GY1", Sex = Sex.Man,IsJoin=true }, new Member() { ID = 2, Name = "GY2", Sex = Sex.Man,IsJoin=false }, new Member() { ID = 3, Name = "GY3", Sex = Sex.Woman,IsJoin=true }, new Member() { ID = 4, Name = "GY4", Sex = Sex.Man ,IsJoin=false} }; this._memberSource.DataSource = this._members; this.bindingNavigator1.BindingSource = this._memberSource; this.dataGridView1.AutoGenerateColumns = false;//停止重繪欄位 this.dataGridView1.DataSource = this._memberSource; createColumns(); this.dataGridView1.AutoGenerateColumns = true;//開始重繪欄位,補足還沒建立的欄位 }
建立DataGridViewComboBoxColumn欄位
void createColumns() { DataGridViewComboBoxColumn columnID = new DataGridViewComboBoxColumn(); columnID.HeaderText = "ID"; columnID.Name = "ID"; columnID.DataPropertyName = "ID"; columnID.Items.AddRange(new object[] { 1, 2, 3, 4 }); DataGridViewComboBoxColumn columnSex = new DataGridViewComboBoxColumn(); columnSex.HeaderText = "Sex"; columnSex.Name = "Sex"; columnSex.DataPropertyName = "Sex"; columnSex.DataSource = Enum.GetValues(typeof(Sex));//建立下拉選單 this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnID, columnSex }); }
結果如下,搞定收工!
後記:dgvBindingEnum.zip
這是一個蠻常見的用法,使用DataGridViewComboBoxColumn可以確保資料能被輸入正確的格式,有一件事必須要注意
它在STA下執行不會有錯誤
不過當一改成MTA後,操作 DataGridViewComboBoxColumn 就會出現以下錯誤