如何在DataGridViewCell中托管控件以进行显示和编辑?

我已经看到如何:Windows窗体DataGridView单元中的主机控件,它解释了如何托管用于编辑DataGridView中的单元格的控件。 但是如何托管用于显示单元格的控件?

我需要在同一个单元格中显示文件名和按钮。 我们的UI设计师是一个平面设计师,而不是程序员,因此我必须将代码与他所绘制的内容相匹配,无论是否可行 – 或明智 – 或不是。 我们正在使用VS2008并使用C#编写.NET 3.5,如果这有所不同的话。

更新:’网络建议创建一个自定义DataGridViewCell,它作为第一步主持一个面板; 有谁做过吗?

根据您的“更新”,创建自定义DataGridViewCell就是这样做的方式。 我已经完成了它,它不需要从MSDN提供的示例代码中进行太多修改。 在我的情况下,我需要一堆自定义编辑控件,所以我最终inheritance了DataGridViewTextBoxCellDataGridViewColumn 。 我插入了我的类(从DataGridViewTextBoxCellinheritance的那个)一个新的自定义控件,它实现了IDataGridViewEditingControl ,而且一切正常。

我想在你的情况下,你可以写一个PanelDataGridViewCell ,它将包含一个控件MyPanelControl ,它将从Panelinheritance并实现IDataGridViewEditingControl

而不是使用datagridview,而是使用TableLayoutPanel。 创建具有标签和按钮以及事件的控件,并使用它们填充布局面板。 你可以说你的控制成了细胞。 如果这是您想要的布局样式,那么使表格布局面板看起来像数据网格视图并不需要太多。

有两种方法可以做到这一点:

1)。 将DataGridViewCell转换为存在的某个单元格类型。 例如,将DataGridViewTextBoxCell转换为DataGridViewComboBoxCell类型。

2)。 创建一个控件并将其添加到DataGridView的控件集合中,设置其位置和大小以适合要作为主机的单元格。

请参阅下面的Zhi-Xin Ye的示例代码,其中说明了这些技巧:

 private void Form_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("name"); for (int j = 0; j < 10; j++) { dt.Rows.Add(""); } this.dataGridView1.DataSource = dt; this.dataGridView1.Columns[0].Width = 200; /* * First method : Convert to an existed cell type such ComboBox cell,etc */ DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell(); ComboBoxCell.Items.AddRange(new string[] { "aaa","bbb","ccc" }); this.dataGridView1[0, 0] = ComboBoxCell; this.dataGridView1[0, 0].Value = "bbb"; DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell(); this.dataGridView1[0, 1] = TextBoxCell; this.dataGridView1[0, 1].Value = "some text"; DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell(); CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; this.dataGridView1[0, 2] = CheckBoxCell; this.dataGridView1[0, 2].Value = true; /* * Second method : Add control to the host in the cell */ DateTimePicker dtp = new DateTimePicker(); dtp.Value = DateTime.Now.AddDays(-10); //add DateTimePicker into the control collection of the DataGridView this.dataGridView1.Controls.Add(dtp); //set its location and size to fit the cell dtp.Location = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Location; dtp.Size = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Size; } 

MSDN参考:如何在DataGridView控件中的同一列中托管不同的控件

使用第一种方法如下所示:

DataGridView列中的不同控件

使用第二种方法如下所示:

在此处输入图像描述

附加信息: 初始化网格时,同一DataGridView列中的控件不呈现