Skip to main content Skip to footer

How To: Cloning Spread

Almost every class within FarPoint.Win.Spread namespace has a Clone() method to clone their object. You can clone Styles, Celltypes, Charts and many other objects but Spread itself does not a have Clone method to allow to make a copy of it. Whereas we may need sometime to make a copy of our existing Spread control which retains the events , styles and formulas from the original Spread. This blog looks to overcome this limitation and help you understand cloning a Spread object using XML Serialization. Following code serialize Spread control with all the formatting to make a clone of it:


'Copying to a memory stream  
Dim ms As New System.IO.MemoryStream()  
FarPoint.Win.Spread.Model.SpreadSerializer.SaveXml(FpSpread1, ms, False)  
ms = New System.IO.MemoryStream(ms.ToArray())  

'Copying from memory stream to clone spread object  
Dim newSpread As New FarPoint.Win.Spread.FpSpread()  
FarPoint.Win.Spread.Model.SpreadSerializer.OpenXml(newSpread, ms)  

Once the Spread is serialized now we need to attach events from the original Spread to cloned Spread. To do this we will get all the events from original Spread and assign them to cloned Spread one by one through Reflection using Delegates:


Dim fInfo As FieldInfo() = GetType(FarPoint.Win.Spread.FpSpread).GetFields(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.[Static])  
For Each field As FieldInfo In fInfo  
   If field IsNot Nothing Then  
         Dim del As [Delegate] = Nothing  
         If field.FieldType.Name.Contains("EventHandler") Then  
            del = DirectCast(field.GetValue(baseObject), [Delegate])  
         End If  

         If del IsNot Nothing Then  
           Dim eInfo As EventInfo = GetType(FarPoint.Win.Spread.FpSpread).GetEvent(del.Method.Name.Substring(del.Method.Name.IndexOf("_"c) + 1))  
           If eInfo IsNot Nothing Then  
             eInfo.AddEventHandler(newSpread, del)  
           End If  
         End If  
    End If  
Next  

Download the attached samples for complete implementation: Sample C# Sample VB.Net

MESCIUS inc.

comments powered by Disqus