Friday, May 27, 2011

Saving and Loading ListView Data in VB.NET

In this tutorial I'm going to show you how to work (saving and loading) with list view. It allows to represent our data in very meaningful ways. We can classify data into groups, columns etc. But the tricky part is in retrieving and saving the contents of listview. I had a hard time trying to figure out how to save and load the data in listview.



So here is the code for saving data of listview
Code:
Public Sub savedata(ByVal lv As ListView, ByVal filename As String)
        Dim items As List(Of ListViewItem) = New List(Of ListViewItem)
        For Each lvi As ListViewItem In lv.Items
            items.Add(lvi)
        Next
        'lvresults.Items.Clear()

        Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim fs As New IO.FileStream(filename, IO.FileMode.Create)
        formatter.Serialize(fs, items)
        fs.Close()
    End Sub
And to load the data back into listview is

Code:
Public Sub loaddata(ByVal lv As ListView, ByVal filename As String)
        Dim items As List(Of ListViewItem)
        lv.Items.Clear()
        Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim fs As New IO.FileStream(filename, IO.FileMode.Open)
        items = DirectCast(formatter.Deserialize(fs), Global.System.Collections.Generic.List(Of ListViewItem))
        fs.Close()
        lv.Items.AddRange(items.ToArray)
    End Sub

Using these two functions is pretty straight forward. For both of the functions you need to pass the name of listview to be saved or loaded, and a filename to/from which the data will be saved/loaded.

Example code:

Dim openDlg As New OpenFileDialog
        openDlg.Filter = ("My application file  (*.maf)|*.maf")
        openDlg.ShowDialog()

        If openDlg.FileName <> "" Then
            listview1.Items.Clear()
            loaddata(listview1, openDlg.FileName)
        End If

2 comments:

GoDaddy Promo Code said...

Nice tip
btw .. do you know how to protect our program from decompiler?
please share with us.
thanks

Jangedoo said...

there are obfuscators available. Google ".NET obfuscators"

Recent Posts