dcsimg
Results 1 to 11 of 11
  1. #1

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Resolved [RESOLVED] ListView - Save And Load Items

    Hello
    i have a two column listview i wanted to know if someone has a method of saving and loading listviews contents! Thanks


    im new to vb.net this is a vb6 code i used in my programs to load and save all in one

    Code:
    'Changed the function return to boolean
    ' to indicate success or failure.
    'Could probably be a Sub since we indicate
    ' failure with the MsgBox
    
    Public Function SaveLoadListbox(L As ListBox, Contents As String) As Boolean
     Dim LSPath As String
     Dim Txt As String
     Dim i As Long
     Dim fh As Long
    
     '***note here, App.Path is the folder where
     'your project is saved.  If not saved it will
     'be the path from which VB was launched.  So if
     'you launch VB from the start menu it will be
     'the VB6.exe path.  If you launch VB from a
     'shortcut, it will be the 'StartIn' Path.
     LSPath = App.Path & "\mytext.txt"
     fh = FreeFile  'get an open file handle
     On Error GoTo LSErr  'most common failure would
                          'be the file doesn't exist
    
     Select Case Contents
    
      Case "Load"
       Open LSPath For Input As fh
       Do While Not EOF(fh)
        Line Input #fh, Txt 'get the text line at a time
        If Len(Txt) Then    ' & add to the ListBox
         L.AddItem Txt
        End If
       Loop
    
    
      Case "Save"
       Open LSPath For Output As fh
       For i = 0 To L.ListCount - 1 'save each line
        Print #fh, L.List(i)        ' of the ListBox
       Next
     End Select
    
     Close fh
     SaveLoadListbox = True 'success
     Exit Function
    LSErr:
     MsgBox "Err: " & Err.Number & " " & Err.Description
    End Function
    
    
    Private Sub Form_Load()
     Debug.Print SaveLoadListbox(List1, "Load")
    End Sub
    
    Private Sub Form_Unload(Cancel As Integer)
     Debug.Print SaveLoadListbox(List1, "Save")
    End Sub

    pic of my listview
    Name:  List.png
Views: 293
Size:  7.3 KB
    Last edited by sinner0636; Jan 20th, 2018 at 06:43 PM.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,667

    Re: ListView - Save And Load Items

    A ListView simply contains text. It's easy enough to read all the text from a ListView with a couple of nested loops; one to read all the items in the list and another to read all the subitems in an item. You can then do anything you want with that text. Text is text. You can put it into a DataTable and save it to a database. You can write it to a text file. Anything you want. It's for you to decide what you want. Reading the data will depend on how it was saved. Reading a text file is easy enough, as is querying a database. You can then populate the ListView using a loop.

    You should spend a bit of time thinking about the logic involved and then try to implement that logic in code instead of expecting to find an existing turnkey solution. Programming is about learning how to perform specific small tasks and then combining those bits of knowledge in whatever way is required for a complex problem. What you want to do is a complex problem and, like any complex problem, it is comprised of smaller, simpler problems. You need to solve those small, simple problems first, then simply combine the partial solutions into one whole.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Re: ListView - Save And Load Items

    yeah started reading a bit about the stream writer/reader starting to put it togeather just trying to figure out how to read it back

    Code:
    Me.ShowInTaskbar = False
            Me.MinimizeBox = False
            Me.MaximizeBox = False
            Me.ListView1.FullRowSelect = True
            Me.ListView1.View = View.Details
            ListView1.CheckBoxes = True
            Me.ListView1.Columns.Add("Type", 150, HorizontalAlignment.Left)
            Me.ListView1.Columns.Add("Value", 150, HorizontalAlignment.Left)
            
            Dim UserDesktop As String = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
    
            If Not DirExists(UserDesktop + "\FilterList.txt") Then
                Dim str(2) As String
                Dim itm As ListViewItem
                For Each path As String In fileTypesToFind
                    str(0) = path
                    str(1) = "True"
    
                    itm = New ListViewItem(str)
                    ListView1.Items.Add(itm)
                    ListView1.Items(ListView1.CheckedItems.Count).Checked = True
                Next
    
            Else
    
                Dim R As StreamReader
                Dim i As Integer
    
                If DirExists(UserDesktop + "\Filterlist.txt") Then
    
    
                End If
            End If
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim W As StreamWriter
            Dim i As Integer
                W = New StreamWriter(UserDesktop + "\Filterlist.txt")
                For i = 0 To ListView1.Items.Count - 1
                    W.WriteLine(ListView1.Items.Item(i).Text + ":" + ListView1.Items.Item(i).SubItems(1).Text)
                Next
                W.Close()
        End Sub
    Last edited by sinner0636; Jan 20th, 2018 at 07:20 PM.

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,667

    Re: ListView - Save And Load Items

    There are lots of examples of reading delimited text around. Create a StreamReader, loop until the end of the stream, read a line, split it on the delimiter, create a ListViewItem. Add those items to a collection as you go and then, when you're done, add them all to the ListView with one call to AddRange.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Re: ListView - Save And Load Items

    i found a example got it working for the stream read from the saved txt. The problem i am having now is when i check a checkbox i want the sub item that is the second columns rows text to change to the value of the listviews checkbox clicked values

    for example if i check a checkbox on any row i want that same row in the column next to its text to turn to that value of the checkbox i clicked
    i been messing around trying to get it to work any ideas?

    Code:
        Private Sub ListView1_ItemChecked(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles ListView1.ItemChecked
            Try
    
                For i As Integer = 0 To ListView1.Items.Count - 1
                    Me.ListView1.SelectedItems(i).SubItems(1).Text = CStr(Me.ListView1.Items(i).Checked)
                Next
            Catch ex As Exception
                'err
            End Try
        End Sub
    Last edited by sinner0636; Jan 20th, 2018 at 08:56 PM.

  6. #6

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Re: ListView - Save And Load Items

    here is the code i converted from VB6 code above to load save a txt file to listview would it be good idea to save with a button on the form other then using the closing form event to save the listview or does it not matter just thought closing form event may make it skip some data?


    Code:
         Public Sub SaveLoadListView(ByVal L As ListView, ByVal Contents As String)
            Try
                Dim Path As String = UserDesktop + "\FilterList.txt"
    
                Select Case Contents
                    Case "Load" 'Load From Txt File
                        Dim R As New StreamReader(Path)
                        Dim strS() As String
                        Do While R.Peek <> -1
                            Dim Itm As New ListViewItem
                            strS = R.ReadLine.Split(CChar(":"))
                            Itm.Text = strS(0).ToString
                            L.Items.Add(Itm)
                            L.SubItems.Add(strS(1).ToString)
                        Loop
                        R.Close()
    
                    Case "Save" 'Save to Txt File
                        Dim W As StreamWriter = New StreamWriter(Path)
                        For i As Integer = 0 To L.Items.Count - 1
                            W.WriteLine(L.Items.Item(i).Text + ":" + L.Items.Item(i).SubItems(1).Text)
                        Next
                        W.Close()
                End Select
            Catch ex As Exception
                'err
            End Try
        End Sub
    Code:
     Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Call SaveLoadListView(ListView1, "Load")
    End Sub
    Last edited by sinner0636; Jan 20th, 2018 at 08:54 PM.

  7. #7
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,667

    Re: ListView - Save And Load Items

    Quote Originally Posted by sinner0636 View Post
    The problem i am having now is when i check a checkbox i want the sub item that is the second columns rows text to change to the value of the listviews checkbox clicked values
    Based on the title, this thread is about loading and saving ListView data. Doing something when an item is checked is completely unrelated to that, so you should start a new thread with a title that describes the new topic and provide just the information that is relevant to that topic.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8
    PowerPoster
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    2,516

    Re: ListView - Save And Load Items

    Quote Originally Posted by sinner0636 View Post
    here is the code i converted from VB6 code above to load save a txt file to listview would it be good idea to save with a button on the form other then using the closing form event to save the listview or does it not matter just thought closing form event may make it skip some data?
    Both methods are required
    * A button or menu command is helpful to save changes at any time without needing to close the form just to save.
    * On form closing usually a message box popup to ask the user save, discard or cancel closing.

    Don't worry about losing data if you save on form close event as this event is the best place to save opened file(s) or program settings

    BTW: It's not good idea to laod and save in one sub, it's better to split into two sub instead of calling one sub with switch parameter.



  9. #9

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Re: ListView - Save And Load Items

    ok ty

  10. #10
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,031

    Re: [RESOLVED] ListView - Save And Load Items

    New to VB but joined in Sep 2nd, 2009????

  11. #11

    Thread Starter
    Addicted Member sinner0636's Avatar
    Join Date
    Sep 2009
    Posts
    233

    Re: [RESOLVED] ListView - Save And Load Items

    Quote Originally Posted by ident View Post
    New to VB but joined in Sep 2nd, 2009????
    that was when i trying to start programming in vb6 but i have only been programming in vb.net for past two months or so i programmed in real basic for a lot of years a lot of the code i do is converting from real basic and vb6 like this i wrote in real basic years ago does the same thing thats above in vb.net rb and vb is similar in ways but RB is much more easy then VB i used to make my own examples in the link below this is the first time i programmed in a year in a half


    http://forums.realsoftware.com/viewt...p?f=21&t=42374

    Code:
    Sub SaveLoadListbox( L As ListBox , Type As String )
      Dim f As folderitem
      Dim Stream As BinaryStream
      Dim Count1,Count2,i,x As Integer
      
      Select Case Type
        
      Case "Save"
        f= New FolderItem( "C:\DataFile")
        If f <> NIL Then
          Stream=f.CreateBinaryFile(".data")
          Stream.WriteLong L.ListCount
          Stream.WriteLong L.ColumnCount
          For i =0 To L.ListCount-1
            For x=0 To L.ColumnCount-1
              Stream.WritePString L.Cell(i,x)
            Next
          Next
          Stream.Close
        End
        
      Case "Load"
        f= GetFolderItem("C:\DataFile")
        If f <> NIL AND f.Exists Then
          Stream=f.OpenAsBinaryFile(False)
          Count1=Stream.ReadLong
          Count2=Stream.ReadLong
          If Count1 = 0 Then Return
          For i =0 To Count1-1
            L.AddRow Stream.ReadPString
            For x=1 To Count2-1
              L.Cell(i,x)=Stream.ReadPString
            Next
          Next
          Stream.Close
        End
      End Select
    End Sub
    
    
    2. Call it like this in a pushbutton or a listbox's open close event
    
    'Save
    Call SaveLoadListbox( listbox1, "Save" )
    'Load
    Call SaveLoadListbox( listbox1, "Load"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width


×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.