Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'' حفظ البيانات في ملف
SerializeListViewData(ListView1, "file.xml")
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'' قراءة البيانات من ملف
DeserializeToListView(ListView1, "file.xml")
End Sub
#Region " Serialize and Deserialize ListView data "
'' http://vbcity.com/blogs/xtab/archive/2011/10/17/how-to-serialize-and-deserialize-listview-data.aspx
' Serialize '
Private Sub SerializeListViewData(LV As ListView, ByVal filename As String)
' Create a FileStream and get the file to write to. '
Dim FS As IO.FileStream = IO.File.Create(filename)
' Create a Binary Formatter for Serialization process '
Dim BinFmtr As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
' Create an arraylist as temp storage for listview items data '
Dim alSavedLV As New ArrayList
' Iterate through the ListView''s listitem collection and add '
' each to the temporary ArrayList '
For item As Integer = 0 To LV.Items.Count - 1
' Add next item/subitem to the arraylist '
alSavedLV.Add(LV.Items(item))
Next
' Serialize the complete arraylist to the file '
' The arraylist contains all the listview data '
BinFmtr.Serialize(FS, alSavedLV)
' Close the FileStream '
FS.Close()
End Sub
' Deserialize '
Private Sub DeserializeToListView(ByVal LV As ListView, ByVal filename As String)
' Create a FileStream to access the storage file '
Dim FS As IO.FileStream = IO.File.Open(filename, IO.FileMode.Open)
' Create a Binary Formatter for Serialization process '
Dim BinFmtr As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
' Create an arraylist as temp storage for listview items data '
Dim alSavedLV As New ArrayList
' Deserialize the data from the file and put it in the arraylist '
alSavedLV = CType(BinFmtr.Deserialize(FS), ArrayList)
' Read the arraylist contents into the listview '
Dim lvi As ListViewItem
For item As Integer = 0 To alSavedLV.Count - 1
lvi = New ListViewItem
lvi = CType(alSavedLV(item), ListViewItem)
LV.Items.Add(lvi)
Next
' Done with the FileStream '
FS.Close()
End Sub
#End Region
End Class