日前,开始用Winform开发程序。DataGridView比起来WebForm中的GridView不知道好用了多少倍!唉,可怜的Web程序员。但是内置的列类型还是不够用,于是按照在Webform中的经验,先定制一些自定义的DataGridViewColumn的子类,便于使用DataGridView。
不得不说的是,在Winform中开发自定义控件确实爽多了,很容易的(对比Webform中)实现了几个自定义列类型,经测试使用还可以,可是就是不支持设计期,明明在列的编辑器中可以察看自定义的属性,也可以修改,但却不能保存,关掉重新打开列编辑器后那几个自定义属性还是一片空白!
未修正的示意代码如下:
public class MyCustomColumnCell : DataGridViewTextBoxCell
{
private int _myCustomProperty;
public int MyCustomProperty
{
get { return _myCustomProperty; }
set { _myCustomProperty = value; }
}
.
.
.
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
MyCustomColumnEditor ctl =
DataGridView.EditingControl as MyCustomColumnEditor;
ctl.MyCustomProperty=this.MyCustomProperty;
ctl.Value = this.Value;
}
}
--------------------------------------------------------------------------------
public class MyCustomColumn : DataGridViewColumn
{
private int _myCustomProperty;
public int MyCustomProperty
{
get { return _myCustomProperty; }
set { _myCustomProperty = value; }
}
.
.
.
}
经过一番上网搜索,终于找到了解决方法,原来需要在自定义的Column类中,覆盖Clone()方法!经过一番修改,测试,^_^果然搞定。废话少说,示意代码如下:{
private int _myCustomProperty;
public int MyCustomProperty
{
get { return _myCustomProperty; }
set { _myCustomProperty = value; }
}
.
.
.
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
MyCustomColumnEditor ctl =
DataGridView.EditingControl as MyCustomColumnEditor;
ctl.MyCustomProperty=this.MyCustomProperty;
ctl.Value = this.Value;
}
}
--------------------------------------------------------------------------------
public class MyCustomColumn : DataGridViewColumn
{
private int _myCustomProperty;
public int MyCustomProperty
{
get { return _myCustomProperty; }
set { _myCustomProperty = value; }
}
.
.
.
}
public override object Clone()
{
MyCustomColumn col = (MyCustomColumn)base.Clone();
col.MyCustomProperty = _myCustomProperty;
return col;
}
{
MyCustomColumn col = (MyCustomColumn)base.Clone();
col.MyCustomProperty = _myCustomProperty;
return col;
}