背景:
WinForms 表单有两个 DataGridView 控件,DataGridView1 和 DataGridView2(SelectionMode 属性设置为 FullRowSelect),如上传的图片所示。这两个 DataGridView 控件都列出产品并具有相同的列集(DataGridView1 中还有一个附加复选框列)。 “数量”列是可编辑的,编辑后“金额”列也会更新。目标是,当在一个 DataGridView 控件中进行更改时,其他 DataGridView 控件中也会反映出相同的情况。
数据模型:
public class Product : INotifyPropertyChanged
{
public string Code { get; set; }
public string Name { get; set; }
private int quantity;
public int Quantity
{
get { return this.quantity; }
set
{
this.quantity = value;
this.OnPropertyChanged();
}
}
}
public class ProductCollection : Collection<Product>
{
}
数据绑定:
BindingSource bs1 = new BindingSource();
bs1.DataSource = pc1; // pc1 is the ProductCollection from database as a result of search
dataGridView1.DataSource = bs1;
BindingSource bs2 = new BindingSource();
bs2.DataSource = new ProductCollection();
dataGridView2.DataSource = bs2;
用途:
...
private void AddProductsButton_Click(sender, e)
{
for (int rowIndex = 0; rowIndex < this.dataGridView1.RowCount; rowIndex++)
{
DataGridViewRow row = this.dataGridView1.Rows[rowIndex];
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[0];
if (cell.IsChecked())
{
Product product = (Product)row.DataBoundItem;
this.bs2.Add(product);
cell.Uncheck();
}
}
}
到目前为止一切顺利!
问题:
我已尝试在所附屏幕截图中描述问题(尽可能多)。
我能够使用以下代码解决问题#2:
private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell && dataGridView1.IsCurrentCellDirty)
{
dataGridView1.EndEdit(DataGridViewDataErrorContexts.Commit);
}
}