Datagridview同一列单元格有textbox和combox(动态替换单元格类型)
动态替换单元格类型
这种方法的核心是在程序运行时,根据条件(如行索引、数据值等)将特定单元格替换为不同类型的单元格对象。
实现步骤
-
设计时列类型:在DataGridView设计器中,根据该列最主要的用途先添加一种列类型,例如
DataGridViewTextBoxColumn。 -
运行时替换:在合适的事件(如
CellClick、CellBeginEdit或数据绑定时)中,通过代码替换特定单元格。
注意:需要先绑定显示数据,然后再修改对应单元格
好处 :所见即所得,看到的就是combox
完整代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace Demo1 12 { 13 public partial class Form3 : Form 14 { 15 public Form3() 16 { 17 InitializeComponent(); 18 } 19 20 private void Form3_Load(object sender, EventArgs e) 21 { 22 //dataGridView1.AutoGenerateColumns = false; 23 //dataGridView1.DataSource = null; 24 25 myDatas.Add(myData); 26 myDatas.Add(myData1); 27 dataGridView1.DataSource = myDatas; 28 29 30 31 32 // 假设 dataGridView1 是你的 DataGridView 控件 33 // 假设要替换的单元格行索引为 1,列索引为 1(第二列) 34 int rowIndex = 1; 35 int columnIndex = 1; 36 37 // 1. 获取当前的文本框单元格 38 DataGridViewTextBoxCell textBoxCell = (DataGridViewTextBoxCell)dataGridView1.Rows[rowIndex].Cells[columnIndex]; 39 40 // 2. 创建一个新的组合框单元格 41 DataGridViewComboBoxCell comboBoxCell = new DataGridViewComboBoxCell(); 42 43 // 3. 为组合框设置数据源(例如,一个字符串数组) 44 string[] items = { "张三", "选项B", "选项C" }; 45 comboBoxCell.Items.AddRange(items); 46 47 // 4. 保留原单元格的值(如果需要) 48 comboBoxCell.Value = textBoxCell.Value; 49 50 // 5. 执行替换操作 51 dataGridView1.Rows[rowIndex].Cells[columnIndex] = comboBoxCell; 52 53 54 55 56 } 57 58 List<MyData> myDatas = new List<MyData>(); 59 MyData myData = new MyData(); 60 MyData myData1 = new MyData(); 61 62 private void button1_Click(object sender, EventArgs e) 63 { 64 string fstr = myDatas[1].Name; 65 MessageBox.Show(fstr); 66 } 67 } 68 69 }

浙公网安备 33010602011771号