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

设置数据源时如何让DataGridView进度条列正常显示数据?

在绑定数据源的DataGridView中使用进度条列的解决方案

你遇到的问题核心是动态替换列的时机不对,导致新添加的进度条列没有正确关联到数据源的绑定上下文,从而无法同步数据。以下是几种可行的解决办法:

方法一:手动定义列后再绑定数据源(推荐)

直接关闭自动列生成,手动添加所有需要的列(包括自定义进度条列),最后绑定数据源,避免动态替换列的问题:

// 关闭自动生成列,避免DataGridView自动创建文本列
myDgv.AutoGenerateColumns = false;

// 添加其他业务列(根据你的数据源属性调整)
myDgv.Columns.Add(new DataGridViewTextBoxColumn 
{ 
    DataPropertyName = "YourOtherProperty", 
    Name = "OtherColumn",
    HeaderText = "其他字段"
});

// 添加自定义进度条列
var progressCol = new CDataGridViewProgressColumn();
progressCol.DataPropertyName = "HelloProgress"; // 绑定数据源中的进度属性
progressCol.Name = "HelloProgress";
progressCol.HeaderText = "进度";
myDgv.Columns.Add(progressCol);

// 最后绑定数据源
myDgv.DataSource = YourDataSource; // 替换为你的实际数据源

方法二:在DataBindingComplete事件中替换列(适配自动生成列场景)

如果必须保留自动生成列的逻辑,不要在ColumnAdded事件中替换,而是在数据绑定完成后的DataBindingComplete事件中操作,此时绑定上下文已经完全建立:

private void myDgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    string targetColName = "HelloProgress";
    // 找到自动生成的文本列
    var textColumn = myDgv.Columns.Cast<DataGridViewColumn>()
        .FirstOrDefault(c => c.DataPropertyName == targetColName 
                          && c.GetType() == typeof(DataGridViewTextBoxColumn));
    
    if (textColumn != null)
    {
        int colIndex = textColumn.Index;
        myDgv.Columns.Remove(textColumn);
        
        // 创建并插入进度条列
        var progressCol = new CDataGridViewProgressColumn();
        progressCol.DataPropertyName = targetColName;
        progressCol.Name = targetColName;
        myDgv.Columns.Insert(colIndex, progressCol);
    }
}

关键检查点:确保自定义进度条列实现正确

确认你的CDataGridViewProgressColumn类正确设置了单元格模板,否则即使绑定正确也无法显示进度条:

public class CDataGridViewProgressColumn : DataGridViewColumn
{
    public CDataGridViewProgressColumn()
        : base(new DataGridViewProgressBarCell()) // 指定单元格模板为进度条单元格
    {
    }

    public override DataGridViewCell CellTemplate
    {
        get => base.CellTemplate;
        set
        {
            // 限制单元格模板类型,避免错误
            if (value != null && !typeof(DataGridViewProgressBarCell).IsAssignableFrom(value.GetType()))
            {
                throw new InvalidCastException("单元格模板必须是DataGridViewProgressBarCell类型");
            }
            base.CellTemplate = value;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:35:26