File I/O and Array Lists Example

These instructions will build an example program that looks like this:

The new button creates an empty record.  The save button will update the current record being viewed.  The delete button will remove the current record being viewed.  You can search for records by typing a person's name in the Search box; the results are shown dynamically while the user types in a search word.

Download the code by clicking on the Zip file.

Instructions for Creating the Example:

  1. Start Visual Studio from the Start menu.
  2. Click on the New Project button in the bottom of the screen.
  3. Select Visual C# Projects, and Windows Application.  In the Name box give your project a name.
  4. Layout your form like this:

The textboxes are called txtName, txtPhone, and txtSearch.  The buttons are called cmdNew, cmdSave, and cmdDelete.  The listbox is called lstResults.

5. At the top of your code add these two lines.  Then create an object for myAddressBook inside the constructor, Form1().

// create an array list, it is like a vector (add/remove elements, and it auto-resizes)
private ArrayList myAddressBook;
// keeps track of the record currently being viewed
private int currentID;

public Form1()
{

    InitializeComponent();

    // create the address book and start it out with 10 records
    myAddressBook = new ArrayList(10);
}

6. Add a "using" statement to the very top of your code window to easily access File I/O classes:

// this contains the StreamWriter and StreamReader classes
using System.IO;

7. Create a new class named Person.  Right click on your Project in the Solution Explorer and choose Add and then Add Class from the context menu.  Choose the name Person.cs for your class file.

8. Our class will contain fields for a record, much like a database table.  In your class, create three public fields:

public class Person
{
    public int ID;
    public string Name;
    public string Phone;

    public Person()
    {
   
    }
}

9. We'll now write three functions inside your form's code to handle the creation, updating, and deletion of records.  The first will create new records, the second will update/save records, and the third will delete records.  Later, we will use these in the events for our buttons.  Place these three functions into your code:

private int CreateNewRecord()
{
    // add a new record to our arraylist, the function will return the ID number
    // associated with the record

    // create a new object of type Person

    Person p = new Person();

    // set the person's ID

    p.ID = myAddressBook.Count;
    p.Name = "";
    p.Phone = "";
    // stick the person in the address book
    myAddressBook.Add(p);

    return p.ID;
}

private void UpdateRecord(int id, string name, string phone)
{
    // update a record with the given ID number using hte Name and Phone # parameters

    // find the record to update using the ID number

    foreach(Person p in myAddressBook)
    {
        // check each object in the address book
        if (p.ID == id)
        {
            p.Name = name;
            p.Phone = phone;
        }

    }
}

private void DeleteRecord(int id)
{
    // remove a record from the array list matching the id

    Person d = new Person();

    foreach(Person p in myAddressBook)
    {
        // check each object in the address book
        if (p.ID == id)
        {
            d = p;
            break;   
        }
    }
    // delete the record
    myAddressBook.Remove(d);
}

10.  Create two functions: one to write out records to a file from memory, and one to read records from a file into memory.

private void SaveRecords()
{
    // writes out the contents of the array list to a file

    // open a file for output, false = don't append

    StreamWriter sw = new StreamWriter("addressbook.txt", false);

    // write out record by record

    foreach(Person p in myAddressBook)
    {
        sw.WriteLine(p.Name);
        sw.WriteLine(p.Phone);
    }
    // close the file

    sw.Close();
}


private void ReadRecords()
{
    // read in all entries from the file to an array list

    // check that the file exists

    if (File.Exists("addressbook.txt"))
    {
        // open a file for input

        StreamReader sr = new StreamReader("addressbook.txt");

        // check if there are more records to get
        // peek will check the next available character but not consume it

        while(sr.Peek() != -1)
        {
            // create an empty record

            currentID = CreateNewRecord();
            // put the name and phone number into the record

            UpdateRecord(currentID, sr.ReadLine(), sr.ReadLine());
        }
        // close the file

        sr.Close();
    }
}


11. Double click on your form to create a Form1_Load event.  Add this code to it so you can move the records from your file into the program's memory.  We also start the program with a new empty record.

private void Form1_Load(object sender, System.EventArgs e)
{
    // load all the records into the array list from the file

    ReadRecords();
    // create a blank record to start with

    currentID = CreateNewRecord();
}

12. Create a click event for the cmdNew button by double clicking on itAdd this code:

private void cmdNew_Click(object sender, System.EventArgs e)
{
    currentID = CreateNewRecord();
    txtName.Text = "";
    txtPhone.Text = "";
}
 

13. Create a click event for the cmdSave button  by double clicking on it.  Add this code:

private void cmdSave_Click(object sender, System.EventArgs e)
{
    UpdateRecord(currentID, txtName.Text, txtPhone.Text);
    // write the records to the file
    SaveRecords();
}

14. Create a click event for the cmdDelete button by double clicking on it.  We will leave a new empty record after we delete the record.  Add this code:

private void cmdDelete_Click(object sender, System.EventArgs e)
{
    // delete the record matching the current ID number
    DeleteRecord(currentID);
    // clear text boxes
    txtName.Text = "";
    txtPhone.Text = "";
    txtSearch.Text = "";
    // start with an empty record
    currentID = CreateNewRecord();
    // write out the records to a file
    SaveRecords();
}

15. Create a TextChanged event for the txtSearch textbox so that when someone types their keyword, the search results will update.  Add this code:

private void txtSearch_TextChanged(object sender, System.EventArgs e)
{
    // search the array list for matching records as the user types

    // clear the results list
    lstResults.Items.Clear();

    // make sure there is something to search for
    if (txtSearch.Text != "")
    {
        foreach(Person p in myAddressBook)
        {
            // try a partial string match, looking at the first few letters of each name only
            if (p.Name != "")
            {
                if (p.Name.Substring(0, txtSearch.Text.Length) == txtSearch.Text)
                {
                    // stick matches in the listbox
                    lstResults.Items.Add(p.Name);
                }
            }
        }
    }

}
 

16. When the user clicks on a search result, it will appear in the main textboxes.  Create a mousedown event for the lstResults listbox.


private void lstResults_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    // make sure something is actually selected in the list

    if (lstResults.SelectedIndex != -1)
    {
        foreach(Person p in myAddressBook)
        {
            if (p.Name == lstResults.Items[lstResults.SelectedIndex])
            {
                // fill in the details on the form
               txtName.Text = p.Name;
               txtPhone.Text = p.Phone;
               currentID = p.ID;
            }
        }
    }
}