我有 3 个对象:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<Order> Orders { get; set; }
public Person()
{
Orders= new List<Order>();
}
}
public class Order
{
public int Id { get; set; }
public string Description { get; set; }
public string Date { get; set; }
public List<Item> Items { get; set; }
public Order()
{
Items= new List<Item>();
}
}
public class Item
{
public int Id { get; set; }
public string ProductName { get; set; }
public int Number { get; set; }
}
如您所见,每个人都可以有多个订单,每个订单可以有多个项目。
在我的应用程序中,来自 DB 的数据如下所示:
private List<Person> _persons;
_persons = new List<Person>
{
new Person
{
Id = 1,
Name = "John",
Surname = "Smith",
Orders = new List<Order>
{
new Order
{
Id = 1,
Description = "First Order",
Date = "2013-03-07",
Items =
new List<Item>
{
new Item {Id = 1, Number = 2, ProductName = "Chair"},
new Item {Id = 2, Number = 1, ProductName = "Bed"}
}
},
new Order
{
Id = 2,
Description = "Second",
Date = "2013-03-07",
Items =
new List<Item>
{
new Item {Id = 1, Number = 2, ProductName = "Pen"},
new Item {Id = 2, Number = 1, ProductName = "Pencil"}
}
}
}
},
new Person
{
Id = 2,
Name = "Adam",
Surname = "West",
Orders = new List<Order>
{
new Order
{
Id = 1,
Description = "Adams order",
Date = "2013-03-07",
Items =
new List<Item>
{
new Item {Id = 1, Number = 2, ProductName = "first"},
new Item {Id = 2, Number = 1, ProductName = "second"}
}
},
new Order
{
Id = 2,
Description = "Adams second",
Date = "2013-03-07",
Items =
new List<Item>
{
new Item {Id = 1, Number = 2, ProductName = "Pen"},
new Item {Id = 2, Number = 1, ProductName = "Pencil"}
}
}
}
}
};
我已经创建了带有 2 个标签和 datagridview 的自定义用户控件,如下所示: 下面是我的代码:
using System.Windows.Forms;
using Demo.Model;
namespace Demo.Controls
{
public partial class OrderView : UserControl
{
private Order _order;
public Order Order
{
get { return _order; }
set
{
_order = value;
UpdateView();
}
}
private void UpdateView()
{
if (_order == null) return;
IdLBL.Text = string.Format("ID: {0}", _order.Id);
DateLBL.Text = string.Format("Date: {0}", _order.Date);
ItemsDGV.DataSource = _order.Items;
}
public OrderView()
{
InitializeComponent();
}
}
}
然后在主窗体中,我将该控件的实例添加到 flowLayoutPanel (针对特定人员的每个订单):
private void RefreshView()
{
flowLayoutPanel1.Controls.Clear();
foreach (Order order in _persons[_currentPerson].Orders)
{
flowLayoutPanel1.Controls.Add(new OrderView {Order = order});
}
}
使用上述数据,我的应用程序如下所示:
我需要能够添加/编辑每个订单的每个项目。添加似乎很容易 - 我将创建新表单,用户将输入详细信息,然后我将进行 DB 调用以添加该项目。
我的问题是:
添加/编辑项目后如何自动刷新视图?我可以以某种方式将我的控件绑定到该列表,每次我更新它我的视图更新。我需要能够向人员添加项目和订单。
最简单的方法是什么?
这种显示方式正确吗?我可以改进它吗?如果是,那怎么办?