C# DataGridView中下拉列表框DataGridViewComboboxColumn的实现
效果图
在winfrom中拖入一个DataGridView控件
private void Form1_Load(object sender, EventArgs e) { DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.Name = "ID"; column.DataPropertyName = "id";//对应数据源的字段 column.HeaderText = "ID"; column.Width = 80; this.dataGridView1.Columns.Add(column); DataGridViewComboBoxColumn column1 = new DataGridViewComboBoxColumn(); column1.Name = "Name"; column1.DataPropertyName = "Name";//对应数据源的字段 column1.HeaderText = "姓名"; column1.Width = 80; this.dataGridView1.Columns.Add(column1); List<string> ListData = new List<string> { "张三", "里斯", "王六" }; column1.DataSource = ListData; //这里需要设置一下combox的itemsource,以便combox根据数据库中对应的值自动显示信息 //绑定数据源 dataGridView1.DataSource = CreateTable(); }
private DataTable CreateTable() { DataTable dt = new DataTable(); //创建一个空表 DataColumn column =new DataColumn(); //创建一个空列 column.DataType = System.Type.GetType("System.Int32"); column.ColumnName = "id"; dt.Columns.Add(column); column = new DataColumn(); column.DataType = Type.GetType("System.String"); column.ColumnName = "Name"; dt.Columns.Add(column); DataRow row = dt.NewRow(); //创建行 row["id"] = 0; row["Name"] = "张三"; dt.Rows.Add(row); //显示 return dt; }
当想修改Combox列的数据时,或是想通过Combox的改变做文章的要用到dataGridView1_EditingControlShowing这个事件,即编辑dataGriview中的数据就会触发该事件
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { ComboBox combo = e.Control as ComboBox; if (combo != null) { combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged); } }
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox combo = sender as ComboBox; string selectedItem = combo.Text;//拿到选择后的值 }
C# winform中datagridview内置的Combobox在点击时需要点击两下才弹出下拉框的解决方法:
将DataGridView属性 EditMode 为 EditOnEnter!
转 : https://www.cnblogs.com/ZLGBloge/p/4415155.html