【问题标题】:How do I prevent a copy of a grid's datasource from not getting changed when the grid's data changes?当网格的数据发生变化时,如何防止网格数据源的副本不被更改?
【发布时间】:2020-05-06 13:11:14
【问题描述】:

这是一个 C# Windows 窗体项目。我在表格上有一个网格。为了获取网格的数据,我运行了一个 SQL 过程并将结果存储在一个类中。我想拥有该类的副本,以便在用户在网格中更改它们之前知道这些值是什么。所以我把这个班级分配给另一个班级。然后我将第一个类指定为网格的数据源。但是,进行更改后,原始类和副本都具有相同的值。如何防止这种情况发生?

这是我的代码:

List<Unreceive> receivedItems = new List<Unreceive>();
List<Unreceive> listItems = mpBLL.GetMPItemsReceived();

receivedItems = listItems;
gcUnreceive.DataSource = listItems;

此时,假设 receivedItems.quantity 和 listItems.quantity 的值为 100。

用户更改网格中的数据,因此数量为 50。触发此代码:

    private void gvUnreceive_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
    {
      DevExpress.XtraGrid.Views.Grid.GridView gridView = (DevExpress.XtraGrid.Views.Grid.GridView) sender;
      int index = gridView.GetDataSourceRowIndex(rowHandle);
      Unreceive selectedItem = listItems[index];
      Unreceive originalItem = receivedItems[index];

      int newQuantity = selectedItem.quantity;
      int originalQuantity = originalItem.quantity;
    }

此时我想要: 新数量 = 50; 原始数量 = 100;

但我得到的是: 新数量 = 50; 原始数量 = 50;

这就像我通过引用而不是通过值传递了一个变量,但我没有在任何地方传递它。如何解决此问题,以使收到的Items 类不受 listItems 类或数据网格发生的影响?

【问题讨论】:

标签: c# winforms pass-by-reference pass-by-value xtragrid


【解决方案1】:

是的,你是对的,它似乎是“byRef”

receivedItems = listItems; “object = object”将共享指向数据所在的指针,创建指向新数据结构的新指针。

您最初在创建新列表时走在了正确的轨道上。 List receivedItems = new List();

您需要遍历原始列表并为副本列表创建新的不同列表项 - 将每个属性设置为主列表的值。这将为您提供两个具有独立内存存储的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多