定义自定义列和单元格类型

使用DataGridView控件,我们已经拥有了比DataGrid丰富得多的功能,因为DataGridView控件直接支持的内置列类型可以用来呈现多种多样的数据类型。当总是有一些特殊的场景需要我们支持显示自定义列。幸运的是,我们可以插入自定义的列和单元格类型,而且DataGridView控件使得这件事变得更加容易

 最终效果图如图1-2所示:


图1-2

首先我们要定义一个自定义的DataGridViewColumn类型的子类型

 Namespace shiboys_CustomeColumnAndCell

{

 class StatusColumn : DataGridViewColumn

{

 public StatusColumn():base(new StatusCell())

{}

private StatusImage m_DefaultImage=StatusImage.Red;

public StatusImage DefaultImage

{

get

 {

       return m_DefaultImage;

}

set

{ m_DefaultImage =value;}

}

/*重写Clone()方法,非常重要,只有重写好了该方法,才能内VS.NET2005 的IDE设计器所捕获,在编辑列类型的下拉列表中,才会有你自己的自定义列类型*/

public override object Clone()

{

 StatusColumn col=base.Clone() as StatusColumn;

 col.DefaultImage= m_DefaultImage;

return col;

}

/*重写CellTemplate目的是:如果有代码试图访问CellTemplate,这段代码将从基类获得,而如果修改之,则会判断单元格类型是否是StatusCell*/

public override DataGridViewCell CellTemplate

{

get{return base.CellTemplate;}

set

 {

   if((value==null) || !(value is StatusCell))

      throw new ArguementException(“非法的单元格类型,StatusColumn列只能装载StatusCell单元格”);

}

}

}

}

2、自定义单元格类型

Namespace shiboys_CustomeColumnAndCell

{

 public enum StatusImage

{ Red,Green,Yellow }

class StatusCell : DataGridViewImageCell

{

 public StatusCell()

 {

   this.ImageLayout=DataGridViewImageCellLayout.Zoom;

}

/*重写GetFormattedValue方法,就像重写Paint方法一样,每次单元格输出的时候,该非法就会被调用,从该方法返回的对象(即下文的image变量)将传递给Paint方法作为格式化后的值来输出,这时DataGridViewImageCell基类将会被调用,并且它期望用作输出的是一个Image值*/

public override object GetFormattedValue(object value,int rowIndex,ref DataGridViewCellStyle cellStyle,TypeConverter valueTypeConverter,TypeConverter formattedValueConverter,DataGridViewDataErrorContexts context)

 {

 string resource=”shiboys_CustomeColumnAndCell.Red.bmp”;

StatusImage statusImg=StatusIamge.Red;

DataGridViewColumn owningCol=OwningColumn as StatusColumn;

//OwingColumn 获取包含此单元格的列

if(owningCol !=null)

statusImg= owningCol.DefaultImage

if(value is int || value is StatusImage)    

statusImg=(StatusImage)value;

switch(statusImg)

{

case StatusImage.Red :

resource=” shiboys_CustomeColumnAndCell.Red.bmp”;

break;

case StatusImage.Green :

resource=” shiboys_CustomeColumnAndCell.Green.bmp”;

break;

case StatusImage.Yellow :

resource=” shiboys_CustomeColumnAndCell.Yellow.bmp”;

break;

}

// GetExecutingAssembly()获取包含当前执行代码的程序集

Assembly assembly=Assembly.GetExecutingAssembly();

/*调用 GetManifestResourceStream方法的时候,再IDE中一定要将项目里面的red.bmp,green.bmp,yellow.bmp三张BMP图片的生成方式选择为嵌入的资源,这样才能被GetManifestResourceStream()方法捕获*/

Stream stream =assembly.GetManifestResourceStream(resource);

Image image=Image.FromStream(stream);

cellStyle.ImageAlignment=DataGridViewContentAlignment.TopCenter;

return image;

}

}

}

posted on 2008-03-11 13:23  shiboys  阅读(731)  评论(0编辑  收藏  举报