C# 在DataGridView中使用自定义控件
我有一个通用的自定义控件,它包含一个文本框和一个按钮。其他自定义控件继承此通用控件并指定具体类型,例如:C# 在DataGridView中使用自定义控件,c#,visual-studio,datagridview,C#,Visual Studio,Datagridview,我有一个通用的自定义控件,它包含一个文本框和一个按钮。其他自定义控件继承此通用控件并指定具体类型,例如: public class CustomerType { public int Id {get; set;} public int Number {get; set;} public string Description {get; set;} } 泛型控件有一个值属性(取决于类型参数)和一个文本属性(取决于类型),该属性可能显示CustomerType.Descri
public class CustomerType
{
public int Id {get; set;}
public int Number {get; set;}
public string Description {get; set;}
}
泛型控件有一个值
属性(取决于类型参数)和一个文本
属性(取决于类型),该属性可能显示CustomerType.Description
或ProductType.Name
)
这些控件用于搜索(例如客户类型、产品类型等)
这些控件放置在正常窗体上时工作正常。现在,我需要在DataGridView列中放置这样的控件,所以我尝试遵循这一点
目前,两个派生类如下所示:
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);
}
}
}
但是该列仍然显示一个文本框,而不是我的自定义控件。我错过了什么?此外,如何以及在何处保存网格中单元格的
值
属性?您尚未覆盖CustomerTypeCell的编辑类型
。这就是为什么它仍然显示默认编辑控件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属性存储在其中