English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation of Deep Copy in C# via Serialization, and the Method to Initialize and Refresh DataGridView

In winfrom, the DataGridView's cell will modify its data source when editing. If we encounter a situation like this, we need to refresh the data source to its original state. At this time, either we need to re-obtain and bind the data source, or we can bind the processing by copying a copy of the original file's data. This section introduces the copy method of processing.

The basic code is as follows:

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

[Serializable]
public class DtoColumn : ICloneable2. Implement the Clone interface method: 
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. Achieve the purpose of refreshing by copying a copy of the 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();
});

This article, which implements deep copy in C# and initializes the DataGridView refresh method, is all the content that the editor shares with everyone. I hope it can provide a reference for everyone and I hope everyone will support and cheer for the tutorial.

You May Also Like