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

时间:2008-10-22 14:27:58

标签: c# .net datagridview user-interface

我见过How to: Host Controls in Windows Forms DataGridView Cells,它解释了如何托管用于编辑DataGridView中单元格的控件。但是如何托管显示单元格的控件呢?

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

更新:'net建议创建一个自定义DataGridViewCell,作为第一步托管面板;有人这样做过吗?

3 个答案:

答案 0 :(得分:3)

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

我认为在您的情况下,您可以编写一个PanelDataGridViewCell,其中包含一个控件MyPanelControl,该控件将从Panel继承并实现IDataGridViewEditingControl

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

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 Reference : how to host different controls in the same column in DataGridView control

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

Different Controls in DataGridView Column

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

enter image description here

其他信息:Controls in the same DataGridView column dont render while initializing grid

相关问题