在DataGridView中使用自定义控件

时间:2015-02-03 13:08:38

标签: c# visual-studio datagridview

我有一个通用的自定义控件,其中包含一个文本框和一个按钮。其他自定义控件继承自此通用控件并指定具体类型,例如:

public class CustomerType
{
    public int Id {get; set;}
    public int Number {get; set;}
    public string Description {get; set;}
}

通用控件具有Value属性,该属性取决于Type参数和Text属性,具体取决于类型,可能会显示CustomerType.DescriptionProductType.Name

这些控件用于搜索(例如客户类型,产品类型等)。

这些控件放置在普通表格上时可以正常工作。现在我需要在DataGridView列中放置这样的控件,所以我尝试按照MSDN article进行操作。

目前,2个派生类看起来像这样:

public class CustomerTypeColumn : DataGridViewColumn
{
    public CustomerTypeColumn()
        : base(new CustomerTypeCell()) 
    { }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            if (value != null && !value.GetType().IsAssignableFrom(typeof(CustomerTypeCell)))
            {
                throw new InvalidCastException("Should be CustomerTypeCell.");
            }

            base.CellTemplate = value;
        }
    }
}

public class CustomerTypeCell : DataGridViewTextBoxCell
{
    public CustomerTypeCell() 
        : base() 
    { }

    public override Type ValueType
    {
        get
        {
            return typeof(CustomerType);
        }
    }
}

但该列仍然显示文本框而不是我的自定义控件。我在这里错过了什么?此外,我将如何以及在何处保存网格中单元格的Value属性?

1 个答案:

答案 0 :(得分:0)

您还没有覆盖EditType的{​​{1}}。但是它仍然显示CustomerTypeCell的默认编辑控件DataGridViewTextBoxCell

您必须创建自定义编辑控件,就像在您引用的MSDN链接中一样,或者在自定义控件中实现TextBox控件。在IDataGridViewEditingControl

中返回自定义编辑控件的类型
EditType

单元格已具有值属性。将控件的value属性存储在其中。