65.9K
CodeProject 正在变化。 阅读更多。
Home

带跨度行为的 DataGridViewTextBoxCell

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (41投票s)

2009年3月10日

CPOL

1分钟阅读

viewsIcon

298935

downloadIcon

17703

派生自 DataGridViewTextBoxCell 的单元格,可以与相同类型的单元格合并

引言

标准的 System.Windows.Forms.DataGridView 单元格不支持常规的合并方式。在一些论坛上,开发者建议使用 DataGridViewCellPainting 事件。但如果需要实现复杂的合并,这种方案并不理想。DataGridViewTextBoxCellEx 支持跨列/跨行,无需任何额外的代码。

Using the Code

要在项目中使用的 DataGridViewTextBoxCellEx,请包含 DataGridViewTextBoxCellEx.cs 文件,然后在 DataGridView 控件的列编辑器中添加 DataGridViewTextBoxColumnEx

通过设置目标区域左上角 DataGridViewTextBoxCellEx 单元格的 ColumnSpanRowSpan 属性来执行单元格合并。为了成功合并,目标区域的所有单元格必须是 DataGridViewTextBoxCellEx 类型。

var cell = (DataGridViewTextBoxCellEx)dataGridView1[0, 0];
cell.ColumnSpan = 3;
cell.RowSpan = 2;

例如,dataGridView1[0, 0] 单元格将占据从 (0, 0) 到 (2, 1) 的区域(参见顶部截图)。合并后的单元格将显示为该区域的左上角单元格。如果您想访问合并后的单元格,需要访问合并区域的左上角单元格。合并区域将表现和行为如同一个正常的 System.Windows.Forms.DataGridViewTextBoxCell。您可以像往常一样编辑它(按 F2、单击或键入文本)。

DataGridViewTextBoxCellEx 还具有一个 OwnerCell 属性。对于未合并的单元格以及合并区域的左上角单元格,该属性为 null。对于合并区域的其他单元格,该属性指向左上角单元格。

历史

  • 2009 年 3 月 11 日:初始发布
  • 2010 年 3 月 9 日:更新文章
  • 2010 年 12 月 21 日:更新演示和源代码文件
© . All rights reserved.