【问题标题】:Use a custom control in DataGridView在 DataGridView 中使用自定义控件
【发布时间】:2015-02-04 18:26:23
【问题描述】:

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

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

通用控件有一个Value 属性,它取决于Type 参数和一个Text 属性,根据类型,它可能显示CustomerType.Description 或ProductType.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 属性?

【问题讨论】:

    标签: c# visual-studio datagridview


    【解决方案1】:

    您尚未覆盖CustomerTypeCell 的EditType。那为什么它仍然显示DataGridViewTextBoxCell 的默认编辑控件TextBox。

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

    public class CustomerTypeCell : DataGridViewTextBoxCell
    {
        public CustomerTypeCell() 
            : base() 
        { }
    
        public override Type ValueType
        {
            get
            {
                return typeof(CustomerType);
            }
        }
    
        public override Type EditType
        {
            get
            {                 
                return typeof(CustomEditingControl);
            }
        }       
    }
    

    单元格已经有一个 value 属性。将控件的 value 属性存储在其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多