当使用 DataGridView 时,人们倾向于直接摆弄行和单元格。虽然这是可能的,但通过属性 DataSource 使用数据绑定要容易得多。
使用 Visual Studio 设计器,您已经添加了 DataGridView 和要显示的列。虽然可以定义哪个列应该显示哪个属性,但在构造函数中更容易做到这一点。
可惜你忘了告诉我们你想显示什么项目,所以假设你想显示Product的几个属性:
class Product
{
public int Id {get; set;}
public string Description {get; set;}
public decimal Price {get; set;}
public int Stock {get; set;}
...
}
假设您想在 DataGridView 中将这些值显示为列。在构造函数中,您将编写:
public MyForm()
{
InitializeComponent(); // Creates the DataGridView and the columns
// define which column should show which property
this.ColumnId.DataPropertyName = nameof(Product.Id);
this.ColumnDescription.DataPropertyName = nameof(Product.Description);
this.ColumnPrice.DataPropertyName = nameof(Product.Price);
this.ColumnStock.DataPropertyName = nameof(Product.Stock);
... // etc, for all Product properties that you want to show
}
在某个地方,您将有一种从数据库中获取产品的方法:
private IEnumerable<Product> FetchProductsToDisplay()
{
... // TODO: implement; out of scope of this question
}
要显示产品:通过 BindingList<Product> 将它们分配给 DataGridView 的数据源:
private BindingList<Product> DisplayedProducts
{
get => (BindingList<Product>)this.DataGridView1.DataSource;
set => this.DataGridView1.DataSource = value;
}
在加载表单时,或在某些其他事件之后,您需要使用 Products 填充 datagridview:
private void InitializeTableProducts()
{
IEnumerable<Product> productsToDisplay = this.FetchProductsToDisplay();
this.DisplayedProducts = new BindingList<Product>(productsToDisplay.ToList());
}
这足以显示产品。操作员可以根据您在列和数据网格视图中定义的可编辑性添加/删除产品和编辑单元格。如果允许,他甚至可以重新排列行和列。
当操作员完成编辑后,他会通知软件,例如按下 OK 按钮:
private void OnButtonOk_Clicked(object sender, ...)
{
this.ProcessEditedProducts();
}
private void ProcessEditedProducts()
{
ICollection<Product> editedProducts = this.DisplayedProducts;
this.ProcessProducts(editedProducts);
}
在 ProcessProducts 中,您必须找出添加/删除/更改了哪些产品。我假设您会通过零 ID 识别已编辑的产品。
要确定一个产品是否被删除:它将在原始数据库中有一个 Id,但在editedProducts 中没有。
更改产品更难:您需要按价值进行比较。为此,您需要创建一个IEqualityComparer<Product>。
我假设您知道如何检查产品是否被添加/删除/更改的技术。