简体   繁体   中英

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:

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: 在此处输入图片说明

What I want to do is to reload the DataGridView bound to the order List, hence I tried the following code:

        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. And also you can try this inside your for loop,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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