WinForms DataGridView 行刷新问题

问题描述 投票:0回答:1

背景:

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;

用途:

  1. 用户执行搜索并加载一个或多个产品 根据搜索文本从数据库中获取 DataGridView1。
  2. 用户然后根据需要编辑数量列,这会更新 相应的金额栏。
  3. 然后用户使用每个产品的复选框来选择产品 行,然后单击“添加到产品列表”按钮添加 选定的产品到 DataGridView2。

...

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();
    }
  }
}

到目前为止一切顺利!

问题:

  1. 当一个 DataGridView 控件中的数量列更新时, 更改仅立即反映在其他 DataGridView 控件中 对于当前突出显示(选定)的行。为一个 未选定的行,更改不会立即反映。而且,只是 当我做任何导致 DataGridView 被重新绘制的事情时, 显示更新的值。
  2. 在DataGridView1中,将选定(选中)的产品添加到 DataGridView2,该单元格以编程方式取消选中(参见代码 多于)。除了这一行之外,所有行的单元格在视觉上都未选中 突出显示(尽管底层单元格值为 false)。和 与上面的问题类似,因为我做了任何导致 DataGridView 重新绘制,复选标记消失。

我已尝试在所附屏幕截图中描述问题(尽可能多)。

DataGridView1:

DataGridView2:

c# winforms data-binding datagridview .net-4.7.2
1个回答
0
投票

我能够使用以下代码解决问题#2:

private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
  if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell && dataGridView1.IsCurrentCellDirty)
  {
    dataGridView1.EndEdit(DataGridViewDataErrorContexts.Commit);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.