简体   繁体   English

C#:用类对象列表填充DataGridView

[英]C#: Fill DataGridView with List of Class Objects

I have the following class which fills a list as shown bellow from an event when a button bound to each column is clicked on a DataGridView called MenuGrid: 我有以下类,当在名为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() });
}

This MenuGrid has the following format: 此MenuGrid具有以下格式: 在此处输入图片说明

What I want to do is to reload the DataGridView bound to the order List, hence I tried the following code: 我想做的是重新加载绑定到订单列表的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();

This gives the following output, which is not what I want: 这给出了以下输出,这不是我想要的:

在此处输入图片说明

The final screenshot is correct on the number of rows but it doesn't include the name and the price of the the item. 最终的屏幕截图在行数上是正确的,但其中不包括商品的名称和价格。

Any suggestions? 有什么建议么?

Dont set DataSource to null. 不要将DataSource设置为null。 And also you can try this inside your for loop, 而且您也可以在for循环中尝试此操作,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM