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

C# WinForm中如何将DataGridView绑定到类中的数据

解决C# WinForm中Invoice数据绑定到DataGridView的问题

核心问题是DataGridView默认无法直接识别嵌套对象的属性,你的SoldItem类里包含了嵌套的Item对象,需要通过指定列的DataPropertyName来关联嵌套属性,同时处理计算列(LineTotal)的显示。

步骤1:修改SoldItem类(添加计算属性,可选)

如果想直接绑定LineTotal,可以给SoldItem添加一个计算属性,自动计算单行总价:

class SoldItem
{
    public int QuantitySold { get; set; }
    public Item ItemSold { get; set; }
    public SoldItem(int quantitySold, Item itemSold) {
        QuantitySold = quantitySold;
        ItemSold = itemSold;
    }
    // 计算单行总价,空值处理避免报错
    public double LineTotal => QuantitySold * (ItemSold.SellingPrice ?? 0);
}

步骤2:配置DataGridView列的绑定关系

在窗体初始化列的代码中,给每个列指定DataPropertyName,关联到对应的类属性(包括嵌套属性):

// 初始化DataGridView列时添加以下配置
this.Item.HeaderText = "Item Description";
this.Item.Name = "Item";
this.Item.DataPropertyName = "ItemSold.ItemName"; // 绑定嵌套的ItemName属性

this.Quantity.HeaderText = "Quantity";
this.Quantity.Name = "Quantity";
this.Quantity.DataPropertyName = "QuantitySold"; // 直接绑定QuantitySold

this.Price.HeaderText = "Price";
this.Price.Name = "Price";
this.Price.ReadOnly = true;
this.Price.DataPropertyName = "ItemSold.SellingPrice"; // 绑定嵌套的SellingPrice

this.LineTotal.HeaderText = "Line Total";
this.LineTotal.Name = "LineTotal";
this.LineTotal.ReadOnly = true;
this.LineTotal.DataPropertyName = "LineTotal"; // 绑定计算属性

步骤3:绑定数据源到DataGridView

在setupForm方法末尾添加数据源绑定代码,把Invoice的ListSoldItem赋值给DataGridView:

private void setupForm() {
    Invoice invoice = new Invoice();
    invoice.InvoiceDate = DateTime.Now;
    invoice.Customer = "Frank";
    invoice.ListSoldItem = new BindingList<SoldItem>()
    {
        new (2, new ("Item A", 10)),
        new (4, new ("Item B", 50)),
        new (7, new ("Item C", 150)),
        new (2, new ("Item D", 1000)),
        new (4, new ("Item E", 5)),
        new (7, new ("Item F", 15))
    };

    lblDate.Text = invoice.InvoiceDate.ToString();
    customer.Text = invoice.Customer;

    // 绑定数据源
    dgv.DataSource = invoice.ListSoldItem;
}

替代方案:用CellFormatting事件计算LineTotal(无需修改SoldItem类)

如果不想给SoldItem添加计算属性,可以通过DataGridView的CellFormatting事件动态计算LineTotal:

// 在窗体构造函数或初始化方法中绑定事件
public YourFormName()
{
    InitializeComponent();
    dgv.CellFormatting += dgv_CellFormatting;
}

// 事件处理方法
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 仅处理LineTotal列
    if (dgv.Columns[e.ColumnIndex].Name == "LineTotal" && e.RowIndex >= 0)
    {
        SoldItem soldItem = dgv.Rows[e.RowIndex].DataBoundItem as SoldItem;
        if (soldItem != null)
        {
            double price = soldItem.ItemSold.SellingPrice ?? 0;
            e.Value = soldItem.QuantitySold * price;
            e.FormattingApplied = true; // 标记已完成格式化
        }
    }
}

关键说明

  • DataGridView支持通过.访问嵌套对象的属性,比如ItemSold.ItemName
  • 使用BindingList<SoldItem>作为数据源,后续列表数据变更会自动同步到DataGridView
  • 空值处理(?? 0)避免因SellingPrice为null导致计算报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:45:43