Click here to Skip to main content
15,885,757 members
Articles / Desktop Programming / Windows Forms

ArrayList to File...

Rate me:
Please Sign up or sign in to vote.
2.56/5 (9 votes)
18 Aug 2010CPOL3 min read 60.4K   2.1K   13   14
Demonstrates a very simple way to create and save Multi-Dimensional (Virtual) ArrayLists to text file

Introduction

This is a simple demo on how to save Multi-Dimensional (Virtual) ArrayLists to text file, via a sample application.

application.png

About ArrayList

ArrayList implements the IList interface using an array whose size is dynamically increased as required, the capacity of an ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation; Elements in ArrayList collection can be accessed using an integer index. Indexes in this collection are zero-based; ArrayList accepts a null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported.

As the newer .NET runtimes offer better collections in System.Collections.Generic, ArrayList are not using in many cases.

singleDimArrayList.png

Advantages of ArrayList

  • Automatic Resizing
  • Convenient to use
  • ArrayList has methods that will add, insert, and remove a range of elements
  • Easy to create a thread-safe ArrayList using the Synchronized method
  • etc.

Disadvantages of ArrayList

  • ArrayList is restricted to a single dimension with a lower bound of zero, (but it can be used to store objects, we can use this feature to make the ArrayList Multi-Dimensional (Virtual)).
  • ArrayList is limited to accumulate only Objects
  • Performance wise very slow
  • etc.

Using the Code

This page does not display all the code, but the basic structure. Download the application source for a detailed investigation.

Basic Principle of Making an ArrayList Multi-Dimensional (Virtual)

As we know, ArrayList can be used to store objects. Here we are using this feature to make the ArrayList Multi-Dimensional (Virtual)) as shown below.

Method 1

VB.NET
'First declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner ArrayList
Dim _InnerList As New ArrayList
'Adding data to the inner ArrayList
_InnerList.Add("MyData")
_InnerList.Add ("MoreData")

Now we have to add inner ArrayList to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

VB.NET
_MainList.Add(_InnerList)
multiDimArrayList.png

Method 2

VB.NET
'First declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner element as Object and add data to the inner element
Dim _InnerList As Object

Now we have to add inner element to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

VB.NET
_MainList.Add(_InnerList)
singleDimArrayList.png

Method 3

This time we are going to use a structure as inner element.

VB.NET
Public Structure Contacts
  Private m_FirstName As String
  Private m_LastName As String
  Private m_Phone As String
        Public Property FirstName() As String
            Get
                Return m_FirstName
            End Get
            Set(ByVal value As String)
                m_FirstName = value
            End Set
        End Property
        Public Property LastName() As String
            Get
                Return m_LastName
            End Get
            Set(ByVal value As String)
                m_LastName = value
            End Set
        End Property
        Public Property Phone() As String
            Get
                Return m_Phone
            End Get
            Set(ByVal value As String)
                m_Phone = value
            End Set
        End Property
End Structure
VB.NET
'Then declare a main ArrayList
Dim _MainList As New ArrayList
'Declare the inner element as an instance of  Structure Contacts
Dim _InnerList As New Contacts
'Adding data to the inner element Contacts
_InnerList.FirstName = "Alex"
_InnerList.SecondName = "Tomy"
_InnerList.Phone = "123456789"

Now we have to add inner element to our main ArrayList, so in effect we have a Multi-Dimensional (Virtual) ArrayList.

VB.NET
_MainList.Add(_InnerList)
multiDimArrayListSTRUCTURE.png

Using the Code

This short article is presented as an example (Address Book) with simple steps to save Multi-Dimensional (Virtual) ArrayLists to text file.

The sample application consists of the following files:

solutionexp.png

Contacts.vb (Structure to manage contact details)

cLibrary.vb (Class used to accomplish save ArrayList {Multi-Dimensional} to file using an instance of the structure Contacts)

classdiagram.png

Step 1

First create the structure Contacts
(see Contacts.vb to understand how to..!!)

Step 2

Create a Class to save ArrayList {Multi-Dimensional} to file using an instance of the structure Contacts.

VB.NET
Friend Class cLibrary
'TO DO
End Class

Create a property called Library As ArrayList to manage the Multi-Dimensional ArrayList of structure Contacts.

VB.NET
Public Property Library() As ArrayList
            Get
                Return m_Library
            End Get
            Set(ByVal value As ArrayList)
                m_Library = value
            End Set
End Property

library.png

How to Save an ArrayList to Text File?

VB.NET
Public Sub WriteToFile(ByVal _FileName As String, ByVal _ArrayList As ArrayList)
            Dim oWrite As System.IO.StreamWriter
            oWrite = File.CreateText(_FileName)
            For i As Integer = 0 To _ArrayList.Count - 1
                oWrite.WriteLine(_ArrayList.Item(i))
                'here Overridden Function ToString is used to convert the structure 
                'Contacts to String value before writing to the text file
            Next
            oWrite.Close()
End Sub

How to Read a Text File to ArrayList?

VB.NET
Public Function ReadFromFile(ByVal _FileName As String) As ArrayList
            Dim oRead As System.IO.StreamReader
            Dim _ArrayList As New ArrayList
            Dim _Contacts As New Contacts
            _ArrayList.Clear()
            If (File.Exists(_FileName) = True) Then
                oRead = File.OpenText(_FileName)
                While oRead.Peek <> -1
                    _Contacts.FromString(oRead.ReadLine())
                    _ArrayList.Add(_Contacts)
                End While
                oRead.Close()
            End If
            Return _ArrayList
        End Function

(see cLibrary.vb to understand how to..!!)

Step 3

VB.NET
Public Class FrmMain
   Private _Lib As New cLibrary("ContactsLib.txt")
End Class

How to Add Item(s) to the Library from Form Class?

VB.NET
Dim _Contact As New Contacts
_Contact.FirstName = Trim(Me.TB_FirstName.Text)
_Contact.LastName = Trim(Me.TB_LastName.Text)
_Contact.Age = Val(Trim(Me.TB_Age.Text))
_Contact.PostBox = Trim(Me.TB_PostBox.Text)
_Contact.Street = Trim(Me.CB_Street.Text)
_Contact.City = Trim(Me.CB_City.Text)
_Contact.Phone = Trim(Me.TB_Phone.Text)
_Contact.Mobile = Trim(Me.TB_Mobile.Text)
_Contact.Email = Trim(Me.TB_Email.Text)
_Lib.Library.Add(_Contact)
_Lib.SaveLibrary()

How to Update an Existing Item in the Library from Form Class?

VB.NET
Dim _Index As Integer = _Lib.IndexOf(Me.CB_SelectContacts.Text)
Dim _Contact As New Contacts
_Contact.FirstName = Trim(Me.TB_FirstName.Text)
_Contact.LastName = Trim(Me.TB_LastName.Text)
_Contact.Age = Val(Trim(Me.TB_Age.Text))
_Contact.PostBox = Trim(Me.TB_PostBox.Text)
_Contact.Street = Trim(Me.CB_Street.Text)
_Contact.City = Trim(Me.CB_City.Text)
_Contact.Phone = Trim(Me.TB_Phone.Text)
_Contact.Mobile = Trim(Me.TB_Mobile.Text)
_Contact.Email = Trim(Me.TB_Email.Text)
_Lib.Library.Item(_Index) = _Contact
_Lib.SaveLibrary()

How to Remove an Existing Item in the Library from Form Class?

VB.NET
If (_Lib.Remove(Me.CB_SelectContacts.Text) = True) Then
            _Lib.SaveLibrary()
End If

How to Retrieve Details of an Existing Item in the Library from Form Class?

VB.NET
Dim _Contact As New Contacts
_Contact = _Lib.GetDetails(Me.CB_SelectContacts.Text)
With _Contact
        Me.TB_FullName.Text = .Name
        Me.TB_FirstName.Text = .FirstName
        Me.TB_LastName.Text = .LastName
        Me.TB_Age.Text = .Age
        Me.TB_PostBox.Text = .PostBox
        Me.CB_Street.Text = .Street
        Me.CB_City.Text = .City
        Me.TB_Phone.Text = .Phone
        Me.TB_Mobile.Text = .Mobile
        Me.TB_Email.Text = .Email
    End With
End Sub

(see FrmMain.vb to understand how to..!!)

Conclusion

There are probably bugs in my code; if you find any, please let me know and I will try to fix it. Comments and suggestions are most welcome.

Hope this can be helpful.
Happy programming!!!

History

  • 18th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNice article Pin
Shane Story25-Aug-10 7:02
Shane Story25-Aug-10 7:02 
GeneralMy vote of 1 Pin
J a a n s19-Aug-10 3:14
professionalJ a a n s19-Aug-10 3:14 
GeneralMy vote of 1 Pin
Michael Sterk18-Aug-10 19:23
Michael Sterk18-Aug-10 19:23 
GeneralMy vote of 2 Pin
ScruffyDuck18-Aug-10 16:40
ScruffyDuck18-Aug-10 16:40 
GeneralMy vote of 2 Pin
karabax18-Aug-10 6:32
karabax18-Aug-10 6:32 
GeneralMy vote of 2 Pin
luisnike1918-Aug-10 6:15
luisnike1918-Aug-10 6:15 
GeneralMy vote of 2 Pin
John Brett18-Aug-10 2:31
John Brett18-Aug-10 2:31 
GeneralI agree with digital man... Pin
Dave Kreskowiak18-Aug-10 2:02
mveDave Kreskowiak18-Aug-10 2:02 
Generalvote for make it public Pin
Pranay Rana18-Aug-10 1:59
professionalPranay Rana18-Aug-10 1:59 
GeneralMy vote of 5 Pin
Pranay Rana18-Aug-10 1:59
professionalPranay Rana18-Aug-10 1:59 
GeneralGood Work..& very colorful article. Pin
Md. Marufuzzaman18-Aug-10 1:51
professionalMd. Marufuzzaman18-Aug-10 1:51 
GeneralSerialize Pin
Trollslayer18-Aug-10 1:39
mentorTrollslayer18-Aug-10 1:39 
GeneralHmm Pin
R. Giskard Reventlov17-Aug-10 23:19
R. Giskard Reventlov17-Aug-10 23:19 
GeneralRe: Hmm Pin
Ajay Vijayvargiya17-Aug-10 23:39
Ajay Vijayvargiya17-Aug-10 23:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.