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

Windows Form中修改DataGridView自定义按钮文本时类型转换报错如何解决

问题原因

  • 类型转换错误:row.Cells["btnSetContact"]获取的是单元格实例,你将其强转为列类型DataGridViewDisableButtonColumn,二者类型不匹配所以抛出转换异常。
  • 属性配置错误:你设置了UseColumnTextForButtonValue = true,代表所有行的按钮文本统一使用列的Text属性值,此时单独修改行级按钮文本不会生效。

解决步骤

  1. 先修改按钮列的初始化配置,将UseColumnTextForButtonValue设为false,允许行级单独配置按钮文本:
var dgvButCol = new DataGridViewDisableButtonColumn()
{
    Name = "btnSetContact",
    Text = "Set Contact",
    HeaderText = "Set",
    UseColumnTextForButtonValue = false // 开启行级按钮文本自定义
};
  1. 遍历行时直接给按钮单元格的Value属性赋值即可,按钮显示的文本默认取Value的值,不需要访问不存在的Text属性:
foreach (DataGridViewRow row in dgvDeliveryBreakdownDesignGroup.Rows)
{
    // 过滤空行/新行,避免空引用报错
    if (row.IsNewRow || row.Cells["HaveDeliveryContact"].Value == null)
        continue;
    
    bool.TryParse(row.Cells["HaveDeliveryContact"].Value.ToString(), out bool haveDeliveryContact);
    if (haveDeliveryContact || lblDeliveryContactName.Text == "None")
    {
        row.Cells["btnSetContact"].Value = "gg";
    }
    else
    {
        // 不符合条件时设置默认显示文本
        row.Cells["btnSetContact"].Value = "Set Contact";
    }
}

如果你的自定义按钮单元格有特殊逻辑,也可以强转成对应单元格类型后再赋值:

((DataGridViewDisableButtonCell)row.Cells["btnSetContact"]).Value = "gg";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:36:08