XTab's Blog

Ged Mead's Blog at vbCity

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

AugSeptember 2008Oct
SMTWTFS
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

Archives

Topics

Ramblings

VB.NET

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 on Sunday, May 27, 2007 10:49 AM

Feedback

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 5/27/2007 5:22 PM Darts
Thanks for core! :)

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/4/2007 10:52 AM Mishaal
Hello there

Thanks a lot for the lesson it ism really what I was looking for

1 - But in your code some thing I cannot understand it the (DataFile) it is not declared from where should I get it or how I declare it

2 - how can I want to save and Read from Microsoft access database can you help me with that?

Thanks in advance

Bye and best regards


# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/4/2007 4:37 PM Ged Mead
Hi Mishaal,
Sorry - I overlooked the line of code that declares the DataFile variable. If you insert a line like the following at the top of the form:
Dim DataFile As String = Application.StartupPath & "\CLBSelected.txt"
(changing the file name if it doesn't suit you) then the code will work fine.
Re using an Access database, this can be done, but does beg the question as to why you would want to use such a heavyweight tool (Access) to save what would be no more than two columns of data?

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/5/2007 7:36 AM Mishaal
Hello Ged

Thanks again for helping me and replaying

The code is working fine for me, the answer of your question why I want to do it on Access Data?
Because I working on program for my friends the program is saving multi-checked box in one filed and read it. I don’t have any idea how to do it since to weeks I’m searching over the Internet for my answer but still nothing

If you have time and would like to help me with the code then I appreciation it and thanks a lot for you

Bye and best regards


# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/5/2007 7:37 AM Mishaal
Hello Ged

Thanks again for helping me and replaying

The code is working fine for me, the answer of your question why I want to do it on Access Data?
Because I working on program for my friends the program is saving multi-checked box in one filed and read it. I don’t have any idea how to do it since to weeks I’m searching over the Internet for my answer but still nothing

If you have time and would like to help me with the code then I appreciation it and thanks a lot for you

Bye and best regards


# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/5/2007 7:37 AM Mishaal
Hello Ged

Thanks again for helping me and replaying

The code is working fine for me, the answer of your question why I want to do it on Access Data?
Because I working on program for my friends the program is saving multi-checked box in one filed and read it. I don’t have any idea how to do it since to weeks I’m searching over the Internet for my answer but still nothing

If you have time and would like to help me with the code then I appreciation it and thanks a lot for you

Bye and best regards


# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/20/2007 9:46 PM john
Hi,

Sorry if this is a stupid question but I am new to VB. when I run the code it complains that StreamWriter, FileStream is not defined. Are these classes which I need to create? or how do i define them?

cheers

john


# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 6/21/2007 7:33 AM Ged
Hi John,
Don't worry - It's not a stupid question. One of those dotNET things that you need to know.
Add an Imports Statement at the top of the form:
Imports System.IO
or
use
SW = New System.IO.StreamWriter(DataFile)

Ged




# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 11/1/2007 7:59 PM ringtones
ring

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 11/1/2007 7:59 PM consolidation debt
debt

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 11/1/2007 7:59 PM free music lyrics
cham

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 11/1/2007 8:00 PM ringtones composer
ring2

# re: CheckedListBox(2) - Saving and Retrieving Checked Items To/From File 11/1/2007 8:00 PM music lyrics
music

Post Feedback

Title:
Name:
Url:
Comments: 
Protected by Clearscreen.SharpHIPEnter the code you see: