You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGridView单元格类型转换异常求助:无法转为自定义单元格类

问题原因

DataGridView在排序、刷新数据源、滚动加载新行等操作后会重新生成单元格实例,此时默认会使用列的CellTemplate创建标准DataGridViewTextBoxCell,而非你自定义的DataGridViewTextBoxCellEx,导致第二次触发CellFormatting事件时类型转换失败。

解决方案

1. 设置列的单元格模板为自定义类型

在初始化DataGridView列时,将对应列的CellTemplate指定为DataGridViewTextBoxCellEx,确保所有新生成的单元格都是自定义类型:

// 代码创建列示例(可在窗体构造/初始化方法中执行)
var donnee1Column = new DataGridViewTextBoxColumn();
donnee1Column.HeaderText = "Donnee1";
donnee1Column.CellTemplate = new DataGridViewTextBoxCellEx(); // 关键:指定自定义单元格模板
dataGridView2.Columns.Add(donnee1Column);

如果是设计器创建的列,可在设计器的列属性面板中找到CellTemplate,选择你的自定义类型。

2. 修改CellFormatting事件代码,增加类型检查与重复设置判断

避免强制转换报错,同时减少不必要的重复操作:

private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dataGridView2.Columns[e.ColumnIndex].HeaderText == "Donnee1")
    {
        // 先检查单元格类型,避免转换异常
        if (dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCellEx cell)
        {
            // 仅当ColumnSpan未设置为目标值时才修改,减少重复操作
            if (cell.ColumnSpan != 2)
            {
                cell.ColumnSpan = 2;
            }
        }
    }
}

额外注意事项

  • 若DataGridView绑定了数据源,需确保数据源更新时不会触发列的重建;如果是自动生成列,要在DataGridView.AutoGenerateColumns事件中手动替换列的CellTemplate。
  • CellFormatting触发频率很高,避免在其中执行复杂操作,影响界面性能。

内容的提问来源于stack exchange,提问作者LiterallyGutsFromBerserk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 04:12:01