XTab's Blog

Ged Mead's Blog at vbCity

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

AprMay 2007Jun
SMTWTFS
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

Archives

Topics

Ramblings

VB.NET

Sunday, May 27, 2007 #

We covered how to check and uncheck individual items in code in a CheckedListBox in Part 1. In this part I want to quickly run through some ways you can save and retrieve user's choices.

Original List
Let's start with a list of items, such as:

Red
Blue
Green
Large
White
Small
House
Pink
Puce
Orange
Black

In our example project they are saved to a plain text file named "Colors.txt".
So the first task is to load this list into the CheckedListBox when the form first loads:

Code Copy
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.CheckedListBox1.CheckOnClick = True
        '  Fill with original list
        Try
            Dim SR As New IO.StreamReader(Application.StartupPath & "\Colors.txt")

            Do While SR.Peek <> -1
                CheckedListBox1.Items.Add(SR.ReadLine)
            Loop
            SR.Close()
        Catch exc As Exception
            ' Report all errors.
            MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read Error " & _
                "Error")
        End Try
    End Sub

Save User's Checked Items
Once the user has made some selections by checking items (or has deleted some items by using the code samples shown in Part 1), we next want to save the user's list to file. This time it's the CheckedIndices collection that holds the key to this task.

The following code snippet will open a file (or create a new one) and save all checked items to that file:

Code Copy
        Dim SW As StreamWriter
        If File.Exists(DataFile) Then
            SW = New StreamWriter(DataFile)

        Else
            ' OR  create this file as it doesn't yet exist
            Dim FS As New FileStream(DataFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)
            SW = New StreamWriter(FS)

        End If
        For i As Integer = 0 To CheckedListBox1.Items.Count - 1
            If CheckedListBox1.CheckedIndices.Contains(i) Then
                SW.WriteLine(CheckedListBox1.Items(i).ToString)
            End If
        Next
        SW.Close()

As you can see, if the CheckedIndices collection contains an item then that item is saved to the text file. If not, then it is skipped.

Reading Back
Just to be sure that it all works as advertised, we should retrieve the user's saved items from the file. This is just basic File IO procedure and no filtering is required because everything in the file will be read into the ListBox:

Code Copy
  '  Clear Previous
        CheckedListBox1.Items.Clear()

        '   Read items from file
        If File.Exists(DataFile) Then
            Try
                Dim SR As New IO.StreamReader(DataFile)

                Do While SR.Peek <> -1
                    CheckedListBox1.Items.Add(SR.ReadLine)
                Loop
                SR.Close()
            Catch exc As Exception
                ' Report all errors.
                MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read Error " & _
                    "Error")
            End Try

        Else : MessageBox.Show("No Data File found!", "Error", MessageBoxButtons.OK)

        End If

So there it is. None of it is rocket science, but if you're unfamiliar with the collections that the CheckedListBox uses it can sometimes be hard to work out just how to complete basic tasks like these.

posted @ 10:49 AM | Feedback (13)