2

我已经看到How to: Host Controls in Windows Forms DataGridView Cells,它解释了如何在 DataGridView 中托管用于编辑单元格的控件。但是我怎样才能拥有一个显示单元格的控件呢?

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

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

4

3 回答 3

3

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

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

于 2009-01-28T06:21:26.170 回答
2

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

于 2009-05-19T06:46:56.580 回答
2

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

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

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

请参阅下面叶志新的示例代码,其中说明了这些技巧:

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 列中的控件不呈现

于 2013-03-03T00:55:26.157 回答