1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[TUT]Working with listview in VB.NET[TUT]

Discussion in 'Visual Basic .NET' started by jangedoo, May 27, 2011.

  1. jangedoo

    jangedoo Registered Member

    Joined:
    Jan 12, 2010
    Messages:
    59
    Likes Received:
    41
    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:

    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
    
    There you have it. Press thanks if you liked it :D
     
    • Thanks Thanks x 1
  2. ryanhackmachine

    ryanhackmachine Regular Member

    Joined:
    May 8, 2010
    Messages:
    380
    Likes Received:
    223
    Occupation:
    Spend Money
    Location:
    In front of my desktop pc
    No i wont
     
  3. jangedoo

    jangedoo Registered Member

    Joined:
    Jan 12, 2010
    Messages:
    59
    Likes Received:
    41
    increasing post counts eh...