DataGridView自定义列

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Winform下DataGridView控件自定义列System.Windows.Forms.DataGridView控件是net下,数据显示使用最多的控件之一,但是Datagridviewk控件列类型却仅仅只有6中

分别是button 、checkbox、combobox、image、link、textbox 等6种常见类型。这很难满足我们日常开发需要。如果需要复杂的应用,要么找第三方控件,要么只能自己开发。而功能强大的第三方控件往往是需要付费的。但我们开发需要的很可能只是简单的功能,如果为了某个简单功能而专门购买一个控件对于个人来说有些得不偿失。

那么我们只剩下自己开发一途。幸运的是DataGridView控件容许我们进行二次开发,可以自定义我们需要的控件列。下图就是自定义日期输入自定义列,通过下面的例子,你完全可以开发出自己需要的功能列。下面给出和C#代码和原理

自定义列必须自己写三个类,这三个类必须继承系统标准的类或实现系统标准接口。这三个类实际上代表gridview控件中的列、列中的单元格、以及单元格中的具体控件

分别继承自系统

1、DataGridViewColumn 代表表格中的列

2、DataGridViewTextBoxCell 代表列中的单元格

3、IDataGridViewEditingControl 接口,单元格控件可以几本可以继承自任何标准控件或者自定义控件,但是必须实现IDataGridViewEditingControl

下面给出vb和C#的详细案例代码

一、C# 代码

using System;

using System.Windows.Forms;

public class CalendarColumn : DataGridViewColumn

{

public CalendarColumn() : base(new CalendarCell())

{

}

public override DataGridViewCell CellTemplate

{

get

{

return base.CellTemplate;

}

set

{

// Ensure that the cell used for the template is a CalendarCell.

if (value != null &&

!value.GetType().IsAssignableFrom(typeof(CalendarCell )))

{

throw new InvalidCastException("Must be a CalendarCell");

}

base.CellTemplate = value;

}

}

}

public class CalendarCell : DataGridViewTextBoxCell

{

public CalendarCell()

: base()

{

// Use the short date format.

this.Style.Format = "d";

}

public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)

{

// Set the value of the editing control to the current cell value.

base.InitializeEditingControl(rowIndex, initialFormattedValue,

dataGridViewCellStyle);

CalendarEditingControl ctl =

DataGridView.EditingControl as CalendarEditingControl;

ctl.Value = (DateTime)this.Value;

}

public override Type EditType

{

get

{

// Return the type of the editing contol that CalendarCell uses.

return typeof(CalendarEditingControl);

}

}

public override Type ValueType

{

get

{

// Return the type of the value that CalendarCell contains.

return typeof(DateTime);

}

}

public override object DefaultNewRowValue

{

get

{

// Use the current date and time as the default value.

return DateTime.Now;

}

}

}

class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl

相关文档
最新文档