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

将List数据绑定到DataGridView时仅显行列无数据如何解决

问题根因

WinForm DataGridView 绑定集合数据源时,仅会自动识别类的公共属性(public property),不会读取私有字段、普通get方法作为数据来源。你当前定义的Product、BulkPurchase类中所有业务字段都是私有成员,仅提供了getName()、getPrice()这类普通获取方法,没有暴露公共属性,因此绑定时无法读取到对应值,才会出现有行列框架但单元格无数据的现象。

修复方案

方案一:修改类定义补充公共属性(推荐)

调整Product和BulkPurchase类的定义,将需要展示的字段对外暴露为公共属性:

// 修改后的Product基类
public class Product
{
    private string name;
    private float price;

    public Product (string prodName, float prodPrice)
    {
        this.name = prodName;
        this.price = prodPrice;
    }

    // 对外暴露公共属性,属性名可自定义,后续绑定需对应
    public string Name => name;
    public float Price => price;        
}
// 修改后的BulkPurchase类
public class BulkPurchase : Product
{
    private int quantity;
    
    public BulkPurchase(string prodName, float prodPrice, int prodQuantity)
        : base(prodName, prodPrice)
    {
        this.quantity = prodQuantity;
    }

    // 数量补充公共属性,方便在表格中展示
    public int Quantity => quantity;
}

修改完成后运行即可正常显示数据,如果是手动配置DataGridView列的场景,只需将每列的DataPropertyName属性设置为对应公共属性的名称(比如Name、Price、Quantity)即可。

方案二:手动填充DataGridView(临时适配)

如果不想修改原有类定义,也可以放弃自动绑定,手动遍历集合添加行:

private void btnCheckout_Click(object sender, EventArgs e)
{
    //切换到结账面板
    pnlMain.Visible = false;
    pnlCheckout.Visible = true;

    // 先清空原有行
    dataGridView1.Rows.Clear();
    // 手动遍历添加行
    foreach (var item in cart)
    {
        dataGridView1.Rows.Add(item.getName(), item.getPrice(), item.quantity);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:06:02