winfrom中DataGridView在的單元格在編輯時候會修改它的數據源的,如果我們遇到這樣一種情景,刷新數據源到原始狀態,這個時候要么數據源的重新獲取綁定,要么通過拷貝一份原始檔的數據再綁定處理,這里介紹拷貝方式處理。
大致代碼如下:
1.目標對需要序列化,并實現ICloneable 接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[Serializable] public class DtoColumn : ICloneable2.實現接口方法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. 通過拷貝一份數據來達到刷新的目的:
1
2
3
4
5
6
7
8
9
|
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(); }); |
以上這篇C#中序列化實現深拷貝,實現DataGridView初始化刷新的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。