I have a class with multiple properties, some of property type in class is datatable
I am using BinaryFormatter to create a clone copy of class, it works fine but datatable.defaultview.sort
that was set with some value does not coping as is in cloned object.
This is a sample code
public static void Main(string[] args)
{
TestCloneDatatable();
}
private static void TestCloneDatatable()
{
DataTable datatatable = new DataTable();
datatatable.Columns.Add("ID", typeof(int));
datatatable.Columns.Add("AddressLine1", typeof(string));
for (int i = 0; i < 10; i++)
{
datatatable.Rows.Add(i, string.Concat("test ", i));
}
datatatable.DefaultView.Sort = "AddressLine1 ASC";
Test test = new Test();
test.ID = 1;
test.Name = "my Name";
test.Addresss = datatatable;
Test testClone = test.Clone();
string sort = testClone.Addresss.DefaultView.Sort; //here it is empty, I need "AddressLine1 ASC" should be there
}
[SerializableAttribute]
public class Test
{
public int ID { get; set; }
public string Name { get; set; }
public DataTable Addresss { get; set; }
public Test Clone()
{
Test result = DeepCopy<Test>(this);
return result;
}
protected T DeepCopy<T>(T item)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new System.IO.MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}
}