[英]C#: Fill DataGridView with List of Class Objects
我有以下類,當在名為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() });
}
我想做的是重新加載綁定到訂單列表的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();
這給出了以下輸出,這不是我想要的:
最終的屏幕截圖在行數上是正確的,但其中不包括商品的名稱和價格。
有什么建議么?
不要將DataSource設置為null。 而且您也可以在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.