背景需求
一个Form窗体,一个Button按钮,一个DataGridView控件,我要实现的是点击按钮,DataGridView控件增加一列。
第一次尝试-报错
1 2 3 4 5 6 7
| private void button1_Click(object sender, EventArgs e) { DataGridViewColumn column = new DataGridViewColumn(); column.Name = "Column0"; column.HeaderText = "选择"; dataGridView1.Columns.Add(column); }
|
问题:
第二次尝试-重复增加这一列
多次单击按钮,就会重复增加这一列
1 2 3 4 5 6 7 8 9
| private void button1_Click(object sender, EventArgs e) { DataGridViewColumn column = new DataGridViewColumn(); column.Name = "Column0"; column.HeaderText = "选择"; DataGridViewCell dgvcell = new DataGridViewTextBoxCell(); column.CellTemplate = dgvcell; dataGridView1.Columns.Add(column); }
|
第三次尝试-达到要求
1 2 3 4 5 6 7 8 9 10
| private void button1_Click(object sender, EventArgs e) { dataGridView1.Columns.Clear(); DataGridViewColumn column = new DataGridViewColumn(); column.Name = "Column0"; column.HeaderText = "选择"; DataGridViewCell dgvcell = new DataGridViewTextBoxCell(); column.CellTemplate = dgvcell; dataGridView1.Columns.Add(column); }
|
相关链接(侵删)
- DataGridView控件中至少有一列没有单元格模板
=================我是分割线=================
欢迎到公众号来唠嗑: