【问题标题】:Making Changes to List Causes DataGridView to show blank对列表进行更改导致 DataGridView 显示空白
【发布时间】:2020-05-16 17:50:40
【问题描述】:

我有一个项目,用户可以在其中添加新产品或修改现有产品。产品可以有与之关联的部件。我在我的产品构造函数所在的类中创建了一个列表来保存每个产品的零件。

我试图弄清楚如何设置,如果用户对与产品关联的部件进行了更改但点击了取消按钮,那么列表将恢复为原始列表。如果他们在对产品部件列表进行编辑后点击保存按钮,则会保存更新的列表,当他们再次打开产品时,会显示更新的列表。

我所拥有的文件中的所有代码都相当多,但我认为对我所拥有的最有帮助的部分是......

在产品文本框中填写产品信息。使用作为 product.Parts 列表副本的 tempParts 列表填充 datagridview CurrentPartsDataGrid。或者,如果是创建的新产品,则创建一个新的空列表。

 if (product != null)
 {
    ProductIdText.Text = product.ID.ToString();
    ProductNameText.Text = product.Name.ToString();
    InvText.Text = product.QOH.ToString();
    PriceText.Text = product.Price.ToString();
    InvMinText.Text = product.Min.ToString();
    InvMaxText.Text = product.Max.ToString();

    tempParts = new BindingList<Part>(product.Parts);
  }
  else
  {
    product = new Product();
    tempParts = new BindingList<Part>();
  }
  CurrentPartsDataGrid.DataSource = tempParts; 

在保存/取消按钮单击事件方法中,我尝试过执行 for 循环或 for each 循环。我清除列表,然后尝试重新填充。

保存中的代码

    product.Parts.Clear();
    foreach (Part part in tempParts)
    { 
       product.Parts.Add(part);
    }

取消中的代码

    tempParts.Clear();

    foreach (Part part in product.Parts)
    {
       tempParts.Add(part);
    }

如果还有什么可以帮助的,请告诉我。我是在这里发帖的新手,所以不想让帖子超载,但也不想提供足够的内容。

任何有关如何解决此问题的帮助都会很棒。

谢谢!

【问题讨论】:

  • 这可能适用于也可能不适用于 BindingList 作为数据源。以下适用于我使用 BindingSource.DataSource = DataTable.DefaultView 其中 DataGridView.DataSource = BindingSource。如果您对 DataGridView 进行编辑,请使用 DataGridView.EndEdit(); 后跟 BindingSource.EndEdit(); 提交它们,否则如果您使用相同的 BindingSource 对控件进行更改,则在 DataGridView.EndEdit(); 之前执行 BindingSource.EndEdit(); 我的意思是,如果您不要使用 EndEdit(); 以适当的顺序提交您的更改,更改可能会空白。
  • 尝试在您的Save(); 过程中加入CurrentPartsDataGrid.EndEdit();
  • 这似乎没有奏效。关于创建新产品的某些事情也没有按预期工作,我认为这也与所有这些麻烦有关。也许是因为我的tempParts = new BindingList&lt;Part&gt; (product.Part); 似乎我最终对tempParts 所做的一切也发生在我不想要的product.Parts 上。

标签: c# list winforms datagridview


【解决方案1】:

我最终不需要做任何 EndEdit() 的事情。

在我的(if product != null)

我加了

 tempList = new BindingList<Part>();
                for (int i = 0; i < product.Parts.Count; i++)
                {
                    tempList.Add(product.Parts[i]);
                }

这创建了一个新的临时列表,当用户选择取消时,我设置了 product.Parts = tempList,从而解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多