DataGridView 控件体系结构(Windows 窗体)

DataGridView 控件及其相关类旨在成为一个灵活、可扩展的系统,用于显示和编辑表格数据。 这些类都包含在 System.Windows.Forms 命名空间中,并且都以“DataGridView”前缀命名。

体系结构元素

主要的 DataGridView 伴随类派生自 DataGridViewElement。 下面的对象模型说明了 DataGridViewElement 继承层次结构。

Diagram that shows the DataGridViewElement Object Model hierarchy.

DataGridViewElement 类提供对父 DataGridView 控件的引用,并具有一个 State 属性,该属性保存一个值,该值表示来自 DataGridViewElementStates 枚举的值的组合。

以下部分更详细地描述了 DataGridView 伴随类。

DataGridViewElementStates

DataGridViewElementStates 枚举包含以下值:

此枚举的值可以与按位逻辑运算符组合,因此 State 属性可以一次表示多个状态。 例如,DataGridViewElement 可以同时是 FrozenSelectedVisible

单元格和带区

DataGridView 控件包含两种基本类型的对象:单元格和带区。 所有单元格都派生自 DataGridViewCell 基类。 DataGridViewColumnDataGridViewRow 这两种带区都派生自 DataGridViewBand 基类。

DataGridView 控件与多个类互操作,但最常见的是 DataGridViewCellDataGridViewColumnDataGridViewRow

DataGridViewCell

单元格是 DataGridView 的基本交互单元。 显示以单元格为中心,数据输入通常通过单元格进行。 可使用 DataGridViewRow 类的 Cells 集合访问单元格,并且可使用 DataGridView 控件的 SelectedCells 集合访问选定的单元格。 下面的对象模型说明了这种用法并显示了 DataGridViewCell 继承层次结构。

Diagram that shows the DataGridViewCell Object Model hierarchy.

DataGridViewCell 类型是一个抽象基类,所有单元格类型都派生自该类。 DataGridViewCell 及其派生类型不是 Windows 窗体控件,而是一些宿主 Windows 窗体控件。 单元格支持的任何编辑功能通常由托管控件处理。

DataGridViewCell 对象不以与 Windows 窗体控件相同的方式控制自己的外观和绘制功能。 相反,DataGridView 负责其 DataGridViewCell 对象的外观。 通过与 DataGridView 控件的属性和事件交互,你可以显著影响单元格的外观和行为。 如果你对超出 DataGridView 控件功能的自定义有特殊要求,你可实现自己的派生自 DataGridViewCell 或其子类之一的类。

下面的列表显示了从 DataGridViewCell 派生的类:

DataGridViewColumn

DataGridView 控件的附加数据存储的架构在 DataGridView 控件的列中表示。 可使用 Columns 集合访问 DataGridView 控件的列。 可使用 SelectedColumns 集合访问选定的列。 下面的对象模型说明了这种用法并显示了 DataGridViewColumn 继承层次结构。

Diagram that shows the DataGridViewColumn Object Model hierarchy.

一些关键单元格类型具有相应的列类型。 它们派生自 DataGridViewColumn 基类。

下面的列表显示了从 DataGridViewColumn 派生的类:

DataGridView 编辑控件

支持高级编辑功能的单元格通常使用派生自 Windows 窗体控件的托管控件。 这些控件还实现了 IDataGridViewEditingControl 接口。 下面的对象模型说明了这些控件的用法。

Diagram showing the DataGridView Editing Control Object Model hierarchy.

DataGridView 控件提供了以下编辑控件:

如需了解如何创建你自己的编辑控件的信息,请参阅如何:在 Windows 窗体 DataGridView 单元格中托管控件

下表说明了单元格类型、列类型和编辑控件之间的关系。

单元格类型 托管控件 列类型
DataGridViewButtonCell 不适用 DataGridViewButtonColumn
DataGridViewCheckBoxCell 不适用 DataGridViewCheckBoxColumn
DataGridViewComboBoxCell DataGridViewComboBoxEditingControl DataGridViewComboBoxColumn
DataGridViewImageCell 不适用 DataGridViewImageColumn
DataGridViewLinkCell 不适用 DataGridViewLinkColumn
DataGridViewTextBoxCell DataGridViewTextBoxEditingControl DataGridViewTextBoxColumn

DataGridViewRow

DataGridViewRow 类显示 DataGridView 控件附加到的数据存储中的记录数据字段。 可使用 Rows 集合访问 DataGridView 控件的行。 可使用 SelectedRows 集合访问选定的行。 下面的对象模型说明了这种用法并显示了 DataGridViewRow 继承层次结构。

Diagram that shows the DataGridViewRow Object Model hierarchy.

可从 DataGridViewRow 类派生自己的类型,但通常没有必要。 DataGridView 控件具有多个与行相关的事件和属性,用于自定义其 DataGridViewRow 对象的行为。

如果启用 DataGridView 控件的 AllowUserToAddRows 属性,用于添加新行的特殊行将显示为最后一行。 此行是 Rows 集合的一部分,但它具有可能需要你注意的特殊功能。 有关详细信息,请参阅在 Windows 窗体 DataGridView 控件中使用新记录行

另请参阅