【问题标题】:C#: Fill DataGridView with List of Class ObjectsC#:用类对象列表填充 DataGridView
【发布时间】:2017-02-11 15:38:37
【问题描述】:

当在名为 MenuGrid 的 DataGridView 上单击绑定到每一列的按钮时,我有以下类填充列表,如下所示:

public class orderedfood
{
     public string price;
     public string item;
}
List<orderedfood> order = new List<orderedfood>();
private void MenuGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
     order.Add(new orderedfood { item = MenuGrid.Rows[e.RowIndex].Cells[1].Value.ToString(), price = subtotal.ToString() });
}

此 MenuGrid 具有以下格式:

我要做的是重新加载绑定到订单列表的DataGridView,因此我尝试了以下代码:

        MenuGrid.DataSource = null;
        MenuGrid.Rows.Clear();


        for (int i = 0; i < order.Count; i++)
        {
            MenuGrid.Rows.Add(order[i].item, order[i].price);


        }
        MenuGrid.Refresh();

这给出了以下输出,这不是我想要的:

最后的截图在行数上是正确的,但它不包括商品的名称和价格。

有什么建议吗?

【问题讨论】:

  • 为什么将数据源设置为空?将数据源设置为order

标签: c# list class datagridview rows


【解决方案1】:

不要将 DataSource 设置为 null。你也可以在你的 for 循环中试试这个,

            DataGridViewRow row = new DataGridViewRow();
            dataGridView1.Rows.Add(row);
            dataGridView1.Rows.Insert(0, order[i].item, order[i].price);

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多