datagridview使用combox
datagridview 使用combox
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { BindData(); } private void BindData() { DataTable dt = new DataTable(); DataColumn dc = new DataColumn("ID"); dt.Columns.Add(dc); dc = new DataColumn("Name"); dt.Columns.Add(dc); dc = new DataColumn("Age"); dt.Columns.Add(dc); dc = new DataColumn("Tel"); dt.Columns.Add(dc); DataRow dr = dt.NewRow(); dr[0] = "001"; dr[1] = "Sam"; dr[2] = "18"; dr[3] = "09xxxxxxxx"; dt.Rows.Add(dr); dr = dt.NewRow(); dr[0] = "002"; dr[1] = "May"; dr[2] = "18"; dr[3] = "09xxxxxxxx"; dt.Rows.Add(dr); #region "自行建立combox 欄位" DataGridViewTextBoxColumn dcText = new DataGridViewTextBoxColumn(); dcText.HeaderText = "ID"; dcText.DataPropertyName = "ID"; this.dataGridView1.Columns.Add(dcText); this.dataGridView1.DataSource = dt; // 繫結dt. this.dataGridView1.Columns.Remove("Age"); // 移除 Age欄位. DataGridViewComboBoxColumn dcCom = new DataGridViewComboBoxColumn(); dcCom.HeaderText = "Age"; dcCom.DataPropertyName = "Age"; // 建立 age欄位 combox 值為1~30. for (int i = 1; i < 30; i++) dcCom.Items.Add(i.ToString()); this.dataGridView1.Columns.Insert(2, dcCom); #endregion } } }