Hi! :icon_biggrin:

I'm trying to program a personal project, but I've hit a bit of a bump in the road.

I've got a Button, a Textbox, and a CheckedListBox; when the button is pressed, whatever is in the TextBox is added to the CheckedListBox. However, when the form is closed and reopened, all of the CheckedListBox's items are no longer present. My CheckedListBox's name in the code is ZapList.

Can someone assist me in, not only saving all of the CheckedListBox's items, but retaining whether or not they were checked as well as the order they were in? I've run out of hair to pull (figuratively) and I really don't want to quit this project, too much effort has gone into it and I'd hate to see it go unfinished like my numerous other projects. :icon_cry:

-Q

Recommended Answers

All 3 Replies

Member Avatar for Unhnd_Exception

Needs error checking.

Private Sub ButtonSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSave.Click
        Dim FileStream As New System.IO.FileStream("C:\CheckedListBoxData.cld", IO.FileMode.Create)
        Dim BinaryWriter As New System.IO.BinaryWriter(FileStream)

        For i = 0 To CheckedListBox1.Items.Count - 1
            BinaryWriter.Write(CStr(CheckedListBox1.Items(i)))
            BinaryWriter.Write(CBool(CheckedListBox1.GetItemChecked(i)))
        Next

        BinaryWriter.Close()
        FileStream.Dispose()
    End Sub

    
    Private Sub ButtonLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLoad.Click
        CheckedListBox1.Items.Clear()

        Dim FileStream As New System.IO.FileStream("C:\CheckedListBoxData.cld", IO.FileMode.Open)
        Dim BinaryReader As New System.IO.BinaryReader(FileStream)

        CheckedListBox1.BeginUpdate()
        Do While FileStream.Position < FileStream.Length
            CheckedListBox1.Items.Add(BinaryReader.ReadString)
            CheckedListBox1.SetItemChecked(CheckedListBox1.Items.Count - 1, BinaryReader.ReadBoolean)
        Loop
        CheckedListBox1.EndUpdate()

        BinaryReader.Close()
        FileStream.Dispose()
    End Sub
commented: Great code! :) +0

You are awesome! That worked 100%! Thank you, I've never felt better at seeing one of my projects functional!

How can I apply this to a SaveFileDialog so I can choose where to save the file?

See if this helps for the SaveFileDialog.

Dim myCoolSaveFileDialog As New SaveFileDialog
        If myCoolSaveFileDialog.ShowDialog = DialogResult.OK Then
            Dim FileStream As New System.IO.FileStream(myCoolSaveFileDialog.FileName, IO.FileMode.Create)
            '// rest of the code here for saving to file.
        End If
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.