Serialization in C Realizes Deep Copy and Realizes Initialization Refresh of DataGridView

  • 2021-12-05 07:05:25
  • OfStack

In winfrom, the cell in DataGridView will modify its data source when editing. If we encounter such a scenario, refresh the data source to the original state. At this time, either the data source is re-acquired and bound, or the data is re-bound by copying a copy of the original file. Here, the copy method is introduced.

The general code is as follows:

1. The target pair needs to be serialized and implement the ICloneable interface:


[Serializable]
public class DtoColumn : ICloneable2. Implementation interface method Clone :  


public object Clone()
{
    using (MemoryStream ms = new MemoryStream(capacity))
    {
      object CloneObject;
      BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
      bf.Serialize(ms, this);
      ms.Seek(0, SeekOrigin.Begin);      
      CloneObject = bf.Deserialize(ms);       
      ms.Close();
      return CloneObject;
    }
}

3. Refresh by copying one copy of data:


private List < dto.DtoColumn > DeepCloneData(List < dto.DtoColumn > rawdata) {
  return rawdata.Select(x = >x.Clone()).Cast < dto.DtoColumn > ().ToList()
}

this.dataGridView1.DoThreadPoolWork(() = >
{
  this.dataGridView1.DataSource = DeepCloneData(CloneInitialColumnData);
  this.dataGridView1.Refresh();
});

Related articles: