Home

File Processing Application: Solo Music Store

     

Introduction

This is an example application that explores file processing, collection classes, and serialization. It shows how to create a simple class whose objects would be used in a collection.

Solo Music Store is a fictitious store that sells musical instruments. In this application, we will show only how to create an inventory of the items.

The application will start with a form from which the user can select an item. The items  are organized by categories and sub-categories.

Practical LearningPractical Learning: Introducing .NET Collection Classes

  1. Start Microsoft Visual Studio and create a new Windows Application named SoloMusicStore1
  2. To create a dialog box, on the main menu, click PROJECT -> Add Windows Form...
  3. Set the name to Category and click Add
  4. Design the form as follows:
     
    Item Category
    Control Text Name Other Properties
    Label Label C&ategory:    
    TextBox Text Box   txtCategory Modifiers: Public
    Button Button &OK btnOK DialogResult: OK
    Button Button &Cancel btnCancel DialogResult: Cancel
    Form Property Value
    FormBorderStyle FixedDialog
    Text Category Editor
    StartPosition CenterScreen
    AcceptButton btnOK
    CancelButton btnCancel
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  5. To create a dialog box, on the main menu, click PROJECT -> Add Windows Form...
  6. Set the name to SubCategory and click Add
  7. Design the form as follows:
     
    Musical Store Item Type
    Control Text Name Other Properties
    Label Label &Sub-Category:    
    TextBox Text Box   txtItemType Modifiers: Public
    Button Button &OK btnOK DialogResult: OK
    Button Button &Cancel btnCancel DialogResult: Cancel
    Form Property Value
    FormBorderStyle FixedDialog
    Text Type Editor
    StartPosition CenterScreen
    AcceptButton btnOK
    CancelButton btnCancel
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  8. To add a new form, on the main menu, click PROJECT -> Add Windows Form...
  9. Set the Name to StoreItemMaintenance and click Add
  10. Complete the design of the form as follows:
     

    Solo Music: Store Item Maintenance

    Control (Name) Text Other Properties
    Label Label   &Item #:  
    Text Box Text Box txtItemNumber    
    Button Button btnFind Find  
    Label Label   C&ategory:  
    Combo Box Combo Box cbxCategories    
    Label Label   &Sub-Category:  
    Combo Box Combo Box cbxSubCategories    
    Label Label   Item &Name:  
    Text Box Text Box txtItemName    
    Label Label   &Unit Price  
    Text Box Text Box txtUnitPrice    
    Button Button btnMaintain   Modifiers: Public
    Button Button btnClose &Close  
    Picture Box Picture Box     Size Mode: Zoom
  11. Click an unoccupied area of the form and, in the Properties window, change the following characteristics:
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  12. Click the Item Number text box
  13. On the Properties window,  click Events and double-click Leave
  14. Implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace SoloMusicStore1
    {
        public partial class StoreItemMaintenance : Form
        {
            public StoreItemMaintenance()
            {
                InitializeComponent();
            }
    
            private void txtItemNumber_Leave(object sender, EventArgs e)
            {
                
            }
        }
    }
  15. To add a new form, on the main menu, click PROJECT -> Add Windows Form...
  16. Set the Name to NewStoreItem and click Add
  17. Design the form as follows:
     

    Solo Music: New Store Item

    Control (Name) Text Other Properties
    Label Label   Item #:  
    Text Box Text Box txtItemNumber   Modifiers: Public
    Label Label   Category:  
    Combo Box Combo Box cbxCategories   Modifiers: Public
    Label Label   Sub-Category:  
    Combo Box Combo Box cbxSubCategories   Modifiers: Public
    Label Label   Item Name:  
    Text Box Text Box txtItemName   Modifiers: Public
    Label Label   Unit Price  
    Text Box Text Box txtUnitPrice   Modifiers: Public
    Button Button btnOK OK DialogResult: OK
    Button Button btnCancel Cancel DialogResult: Cancel
    Picture Box Picture Box     SizeMode: Zoom
  18. Click an unoccupied area of the form and, in the Properties window, change the following characteristics:
    AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  19. Click the Item Number text box
  20. On the Properties window,  click Events and double-click Leave
  21. Implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace SoloMusicStore1
    {
        public partial class NewStoreItem : Form
        {
            public StoreItemMaintenance()
            {
                InitializeComponent();
            }
    
            private void txtItemNumber_Leave(object sender, EventArgs e)
    	{
    	    string strFileName = @"C:\Microsoft Visual C# Application Design\" + txtItemNumber.Text + ".jpg";
    
    	    if (File.Exists(strFileName))
    	        pbxSelectedItem.Image = Image.FromFile(strFileName);
    	    else
            	pbxSelectedItem.Image = Image.FromFile(@"C:\Microsoft Visual C# Application Design\MusicItem.jpg");
    	}
        }
    }
  22. Return to the form and double-click the New Category button
  23. Implement the event as follows:
    private void btnNewCategory_Click(object sender, EventArgs e)
    {
        Category editor = new Category();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            if (!string.IsNullOrEmpty(editor.txtCategory.Text))
            {
                string strCategory = editor.txtCategory.Text;
    
                // Make sure the category is not yet in the list
                if (cbxCategories.Items.Contains(strCategory))
                    MessageBox.Show(strCategory + " is already in the list.",
                                    "Solo Music Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    // Since this is a new category, add it to the combox box
                    cbxCategories.Items.Add(strCategory);
                    // Just in case the user wanted to use this new category
                    // select it
                    cbxCategories.Text = strCategory;
                }
            }
        }
    }
  24. Return to the New Store Item dialog box and double-click the New Sub-Category button
  25. Implement the event as follows:
    private void btnNewSubCategory_Click(object sender, EventArgs e)
    {
        SubCategory editor = new SubCategory();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            if (!string.IsNullOrEmpty(editor.txtSubCategory.Text))
            {
                string strSubCategory = editor.txtSubCategory.Text;
    
                if (cbxSubCategories.Items.Contains(strSubCategory))
                    MessageBox.Show(strSubCategory + " exists already.",
                                    "Solo Music Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    cbxSubCategories.Items.Add(strSubCategory);
                    cbxSubCategories.Text = strSubCategory;
                }
            }
        }
    }
  26. In the Solution Explorer, right-click Form1.cs and click Rename
  27. Change the name to SoloMusicStore and press Enter twice
  28. Design the form as follows:
     

    Musical Instrument Store

     
    Control Text Name Other Properties
    Label Label Item Category    
    Label Label Item Sub-Category    
    Label Label Available Items    
    ListBox List Box   lbxCategories  
    ListBox List Box   lbxSubCategories  
    ListView List View   lvwAvailableItems View: Details
    FullRowSelect: True
    GridLines: True
    Columns
    (Name) Text TextAlign Width
    colItemNumber Item #    
    colItemName Item Name   320
    colUnitPrice Unit Price Right  
    PictureBox   pbxStoreItem SizeMode: Zoom
    Button Button New Store Item... btnNewStoreItem  
    Button Button Update Store Item... btnUpdateStoreItem  
    Button Button Delete Store Item... btnDeleteStoreItem  
    Button Button Close btnClose  
  29. On the Standard toolbar, click the Save All button Save All

The Store Item Class

Each item sold in the store is known for its category and sub-category. Of course, an item must also have a name. Because this a business-based store, each item should (must) alaos have a price.

We will organize all these pieces of information by creating a class named StoreItem.

Practical LearningPractical Learning: Starting a Collection Accessory Class

  1. To create a new class, in the Class View, right-click SoloMusicStore1 -> Add -> Class...
  2. Set the Name to StoreItem and press Enter
  3. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SoloMusicStore1
    {
        [Serializable]
        public class StoreItem
        {
            public string ItemNumber  { get; set; }
            public string Category    { get; set; }
            public string SubCategory { get; set; }
            public string ItemName    { get; set; }
            public double UnitPrice   { get; set; }
    
            public StoreItem()
            {
                ItemNumber = "000000";
                Category = "Miscellaneous";
                SubCategory = "Miscellaneous";
                ItemName = "Unknown";
                UnitPrice = 0.00D;
            }
    
            public StoreItem(string itmNumber, string category,
                             string subCategory, string name, double price)
            {
                ItemNumber = itmNumber;
                Category = category;
                SubCategory = subCategory;
                ItemName = name;
                UnitPrice = price;
            }
    
            public virtual bool Equals(StoreItem same)
            {
                if( (ItemNumber == same.ItemNumber) &&
                    (Category == same.Category) &&
                    (SubCategory == same.SubCategory) &&
                    (ItemName == same.ItemName) &&
                    (UnitPrice == same.UnitPrice) )
                    return true;
                else
                    return false;
            }
    
            public override string ToString()
            {
                return string.Format("Item #:\t{0}\nCategory:\t{1}\n" +
    	                         "Item Type:\t{2}\nItem Name:\t{3}\n" +
            	                 "Unit Price:\t{4}", ItemNumber, Category,
                    		 SubCategory, ItemName, UnitPrice);
            }
        }
    }
  4. On the Standard toolbar, click the Save All button Save All

The Store Items Class

To show the techniques of implementing a .NET collection, we will create a class named StoreItems. This class will implement the IList interface. The class will later be used in our application to create and manage items.

When implementing an interface, you don't have to define all methods. You may have to define only the methods that are necessary for your application.

Practical LearningPractical Learning: Implementing IList

  1. To create a new class, in the Class View, right-click SoloMusicStore1 -> Add -> Class...
  2. Set the Name to StoreItems and press Enter
  3. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SoloMusicStore1
    {
        [Serializable]
        public class StoreItems<T> : IList<T>
        {
        }
    }
  4. In the Code Editor, right-click IList<>, position the mouse on Implement Interface, and click Implement Interface
     
    Implement Interface
  5. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SoloMusicStore1
    {
        [Serializable]
        public class StoreItems<T> : IList<T>
        {
            // This field will be used to keeep a count of
            // the items as they are added or removed
            int counter;
            // This array holds the items of the collection
            private T[] objects;
    
            // The default constructor is used to initialize the collection
            public StoreItems()
            {
                counter = 0;
                objects = new T[10];
            }
    
    	// This method makes it possible to have a collection whose size can increase.
    	// This method checks the size of the array.
    	// If it is too small, its size gets increase.
            private void CheckToIncreaseSize()
            {
                if (counter >= objects.Length)
                    Array.Resize<T>(ref objects, objects.Length + 5);
            }
    
            #region IList<T> Members
    
            public int IndexOf(T item)
            {
                throw new NotImplementedException();
            }
    
            public void Insert(int index, T item)
            {
                throw new NotImplementedException();
            }
    
            public void RemoveAt(int index)
            {
                throw new NotImplementedException();
            }
    
            #endregion
    
            #region ICollection<T> Members
    
            // This indexed property is used to represent an item based on its index
            public T this[int index]
            {
                // The get accessor is used to access the item at a specific index
                get
                {
                    return objects[index];
                }
                // The set accessor can be used to replace the item at a specific index
                // or to add a new item to the end of the collection
                set
                {
                    objects[index] = value;
                }
            }
    
            // This method is used to add a new item to the collection
            public void Add(T item)
            {
                // Find out if the array is getting too small for the next item(s)
                // If it is, increase its size by 5
                CheckToIncreaseSize();
    
                // Add the item at the end
                this.objects[this.counter] = item;
                // Increase the current number of items
                this.counter++;
            }
    
            public void Clear()
    	{
    	    // Delete each item from the collection
    	    foreach (var item in objects)
            	Remove(item);
    
    	    // Reset the number of items of the collection to 0
    	    counter = 0;
    	}
    
            public bool Contains(T item)
            {
                throw new NotImplementedException();
            }
    
            public void CopyTo(T[] array, int arrayIndex)
            {
                throw new NotImplementedException();
            }
    
            public int Count
            {
                get { throw new NotImplementedException(); }
            }
            
            // This property indicates whether the collection can receive new items
            public bool IsReadOnly
            {
                get { return false; }
            }
    
            public bool Remove(T item)
            {
                throw new NotImplementedException();
            }
    
            #endregion
    
            #region IEnumerable<T> Members
    
            public IEnumerator<T> GetEnumerator()
            {
                int number = 0;
    
                while (number < Count)
                {
                    yield return objects[number];
                    number++;
                }
            }
    
            #endregion
    
            #region IEnumerable Members
    
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                int number = 0;
    
                while (number < Count)
                {
                    yield return objects[number];
                    number++;
                }
            }
    
            #endregion
        }
    }

  6. On the Standard toolbar, click the Save All button Save All
 
 
 

Using the Collection Class

Once the collection class is ready, you can use it in your application. Our application uses a class named StoreItems. Since it implements the IList interface, the class is equipped to add and item to the collection, to delete an item from the collection, to locate an item inside the collection, to change the values (update) of a collection, to count the number of items in the collection, etc.

Our application will use serialization to save the collection of items.

The Main Store Form

Our application uses an entry form that presents the items sold in the store. When the application starts, it checks if a store inventory exists. The inventory is stored in a computer file. Therefore, when the application starts, it checks whether that file exists. If it does, the application opens it and stores is records in a variable declared from our collection class.

To present some items, the user selects a category followed by a sub-category, both from two list boxes. The items from the sub-category display in the list view.

Practical LearningPractical Learning: Setting the Read-Only Effect

  1. In the Solution Explorer, double-click SoloMusicStore and double-click an unoccupied area of its body
  2. Implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace SoloMusicStore1
    {
        public partial class SoloMusicStore : Form
        {
            public SoloMusicStore()
            {
                InitializeComponent();
            }
    
            private void InitializeStoreItems()
            {
                StoreItems<StoreItem> items = new StoreItems<StoreItem>();
                BinaryFormatter bfmStoreItem = new BinaryFormatter();
    
                string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
                if (File.Exists(strFileName))
                {
                    using (FileStream stmStoreItem = new FileStream(strFileName,
                                         FileMode.Open,
                                         FileAccess.Read,
                                                         FileShare.Read))
                    {
                        // Retrieve the list of items from file
                        items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
                        // Display the categories in the combo box
                        foreach (StoreItem item in items)
                        {
                            if (!lbxCategories.Items.Contains(item.Category))
                                lbxCategories.Items.Add(item.Category);
                        }
    
                        pbxSelectedItem.Image = Image.FromFile(@"C:\Microsoft Visual C# Application Design\MusicItem.jpg");
                    }
                }
            }
    
            private void SoloMusicStore_Load(object sender, EventArgs e)
            {
                // If this directory and the sub-directory don't exist, create them
                Directory.CreateDirectory(@"C:\Microsoft Visual C# Application Design\Solo Music Store");
                // If the default musical instrument picture is available, show it.
                // If that picture is not found, the application is
                if (File.Exists(@"C:\Microsoft Visual C# ApplicationDesign\default.jpg") )
                    pbxSelectedItem.Image = Image.FromFile(@"C:\Microsoft Visual C# ApplicationDesign\default.jpg");
                // Initialize the Categories list box
                InitializeStoreItems();
            }
        }
    }
  3. Return to the Solo Music Store form and click the Categories list box
  4. In the Properties window, click the Events button and double-click SelectedIndexChanged
  5. Implement the event as follows:
    private void lbxCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        lbxSubCategories.Items.Clear();
        lvwAvailableItems.Items.Clear();
    
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        if (File.Exists(strFileName))
        {
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                 				FileMode.Open,
                                 				FileAccess.Read,
                                                 		FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
    
                // Display the sub-categories in the combo box
                foreach (StoreItem item in items)
                {
                    // Get only the sub-categories of the selected category
                    if (item.Category == lbxCategories.SelectedItem.ToString())
                    {
                        if (!lbxSubCategories.Items.Contains(item.SubCategory))
                            lbxSubCategories.Items.Add(item.SubCategory);
                    }
                }
            }
        }
    }
  6. Return to the Solo Music Store form and click the Sub-Categories list box
  7. In the Events section of the Properties window, double-click SelectedIndexChanged
  8. Implement the event as follows:
    private void lbxSubCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        lvwAvailableItems.Items.Clear();
    
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        if (File.Exists(strFileName))
        {
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Open,
                                                            FileAccess.Read,
                                                            FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
    
                // Display the sub-categories in the combo box
                foreach (StoreItem item in items)
                {
                    // Get only the sub-categories of the selected category
                    if (item.Category == lbxCategories.SelectedItem.ToString())
                    {
                        ListViewItem lviStoreItem = new ListViewItem(item.ItemNumber);
                        lviStoreItem.SubItems.Add(item.ItemName);
                        lviStoreItem.SubItems.Add(item.UnitPrice.ToString("F"));
    
                        lvwAvailableItems.Items.Add(lviStoreItem);
                    }
                }
            }
        }
    }
  9. Return to the Solo Music Store form and click the Available Items list view
  10. In the Events section of the Properties window, double-click ItemSelectionChanged
  11. Implement the event as follows:
    private void lvwAvailableItems_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        string strFileName = @"C:\Microsoft Visual C# Application Design\" + e.Item.Text + ".jpg";
    
        if( File.Exists(strFileName) )
            pbxSelectedItem.Image = Image.FromFile(strFileName);
        else
            pbxSelectedItem.Image = Image.FromFile(@"C:\Microsoft Visual C# Application Design\MusicItem.jpg");
    }
  1. Display the Store Item Maintenance form and double-click the button on the left of Close
  2. Implement the event as follows:
    private void btnMaintain_Click(object sender, EventArgs e)
    {
        bool itemFound = false;
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        // Make sure the user entered a valid item number. Otherwise, don't do nothing
        if (string.IsNullOrEmpty(txtItemNumber.Text))
        {
            MessageBox.Show("You must enter an item number.",
                            "Solo Music Store",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
    
        // Make sure the file that holds the store inventory was created already
        if (File.Exists(strFileName))
        {
            // If the inventory file exists, open it
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Open,
                                                            FileAccess.Read,
                                                            FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
                // Because we are using one dialog box for update and delete operations,
                // first find out what operation is being conducted.
                // If the user is trying to update a store item...
                if (btnMaintain.Text == "Update Store Item")
                {
                    // ... as a courtesy (just in case), ask the user to confirm the operation
                    if (MessageBox.Show("Are you sure you want to update this item?",
                                        "Solo Music Store",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        // Now that we know that the user wants to update the item, locate it
                        foreach (StoreItem item in items)
                        {
                            // If you find an item that has the number in the Item # text box, ...
                            if (item.ItemNumber == txtItemNumber.Text)
                            {
                                // ... change the values of that item based on those on the dialog box
                                item.Category = cbxCategories.Text;
                                item.SubCategory = cbxSubCategories.Text;
                                item.ItemName = txtItemName.Text;
                                item.UnitPrice = double.Parse(txtUnitPrice.Text);
                                // Since the item was found, make a note
                                itemFound = true;
                                // Now that the item has been found, stop looking for it
                                break;
                            }
                        }
    
                        // As a courtesy, let the user know that the item was updated
                        MessageBox.Show("The item has been updated in the inventory.",
                                        "Solo Music Store",
                                        MessageBoxButtons.OK, MessageBoxIcon.Question);
                    }
                }
                else // if (btnMaintain.Text == "Delete Store Item")
                {
                    // Make sure the user really wants to delete the item 
                    if (MessageBox.Show("Are you sure you want to delete this item?",
                                        "Solo Music Store",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        // Since the user really wants to delete the item, look for it
                        foreach (StoreItem item in items)
                        {
                            // If you find the item, ...
                            if (item.ItemNumber == txtItemNumber.Text)
                            {
                                // ... remove it from the inventory
                                items.Remove(item);
                                // Let the user know that the item was deleted
                                MessageBox.Show("The item has been removed from the inventory.",
                                                "Solo Music Store",
                                                MessageBoxButtons.OK, MessageBoxIcon.Question);
                                // Since the item was found and deleted, make a note
                                itemFound = true;
                                // Stop looking for the item
                                break;
                            }
                        }
                    }
                }
            }
    
            // Since there have been changes in the inventory (the StoreItems collection), update the file
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Create,
                                                            FileAccess.Write,
                                                            FileShare.Write))
            {
                bfmStoreItem.Serialize(stmStoreItem, items);
            }
        }
    
        // If the item was updated or deleted, close the dialog box
        if (itemFound == true)
            Close();
    }
  3. Return to the form and double-click the Close button
  4. Implement the event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  5. Display the Solo Music Store form and double-click the Update Store Item...
  6. Implement the event as follows:
    private void btnUpdateStoreItem_Click(object sender, EventArgs e)
    {
        StoreItemMaintenance sim = new StoreItemMaintenance();
    
        sim.btnMaintain.Text = "Update Store Item";
        sim.ShowDialog();
    
        InitializeStoreItems();
    }
  7. Return to the Solo Music Store form and double-click Delete Store Item
  8. Implement the event as follows:
    private void btnDeleteStoreItem_Click(object sender, EventArgs e)
    {
        StoreItemMaintenance sim = new StoreItemMaintenance();
    
        sim.cbxCategories.Enabled = false;
        sim.cbxSubCategories.Enabled = false;
        sim.txtItemName.Enabled = false;
        sim.txtUnitPrice.Enabled = false;
        sim.btnMaintain.Text = "Delete Store Item";
        sim.ShowDialog();
    
        InitializeStoreItems();
    }
  9. Return to the Solo Music Store and double-click the Close button
  10. Implement the event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  11. On the Standard toolbar, click the Save All button Save All

Creating a New Item

We have a form, or rather a dialog box, that can be used to add a new item to the inventory. That dialog box is called from the main form where the user would click a button.

Practical LearningPractical Learning: Adding an Item to the Collection

  1. In the Solution Explorer, double-click SoloMusicStore.cs
  2. On the form, double-click the New Store Item... button
  3. Implement the event as follows:
    private void btnNewStoreItem_Click(object sender, EventArgs e)
    {
        lbxSubCategories.Items.Clear();
        lvwAvailableItems.Items.Clear();
        NewStoreItem nsi = new NewStoreItem();
    
        StoreItem item = new StoreItem();
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        if (nsi.ShowDialog() == DialogResult.OK)
        {
            // Make sure the user had selected a category
            if (string.IsNullOrEmpty(nsi.cbxCategories.Text))
            {
                MessageBox.Show("You must specify the item's category.",
                                "Solo Music Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Make sure the user had entered a name/description
            if (string.IsNullOrEmpty(nsi.txtItemName.Text))
            {
                MessageBox.Show("You must enter the name (or a " +
                                "short description) for the item.",
                                "Solo Music Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Make sure the user had typed a price for the item
            if (string.IsNullOrEmpty(nsi.txtUnitPrice.Text))
            {
                MessageBox.Show("You must enter the price of the item.",
                                "Solo Music Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Before saving the new item, find out if there was
            // already a file that holds the list of items
            // If that file exists, open it and store its items 
            // in our StoreItems list
            if (File.Exists(strFileName))
            {
                using (FileStream stmStoreItem = new FileStream(strFileName,
                    	                                    FileMode.Open,
            	        	                	    FileAccess.Read,
    	                        		            FileShare.Read))
                {
                    // Retrieve the list of items from file
                    items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
                }
            }
    
            // Create the music item
            item.ItemNumber = nsi.txtItemNumber.Text;
            item.Category = nsi.cbxCategories.Text;
            item.SubCategory = nsi.cbxSubCategories.Text;
            item.ItemName = nsi.txtItemName.Text;
            item.UnitPrice = double.Parse(nsi.txtUnitPrice.Text);
    
            // Call the Add method of our collection class to add the item
            items.Add(item);
    
            // Save the StoreItems collection
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                    	                FileMode.Create,
            	        	        	        FileAccess.Write,
    	        	                            	FileShare.Write))
            {
                bfmStoreItem.Serialize(stmStoreItem, items);
            }
        }
    
        InitializeStoreItems();
    }

Item Maintenance

Item maintenance will consist of updating an item (which consists of changing one or more of its values), deleting it (which consists of removing the item from the collection). Of course, when a maintenance operation has been performed, the collection will have changed and must be updated. It is not just the collection that is changed, the file that holds the inventory must also be updated and changed.

Practical LearningPractical Learning: Adding an Item to the Collection

  1. In the Solution Explorer, double-click StoreItemMaintenance and double-click Find
  2. Implement the event as follows:
    private void txtItemNumber_Leave(object sender, EventArgs e)
    {
        btnFind_Click(sender, e);
    }
    
    private void btnFind_Click(object sender, EventArgs e)
    {
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        if (string.IsNullOrEmpty(txtItemNumber.Text))
        {
            MessageBox.Show("You must enter an item number.",
                            "Solo Music Store",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
    
        if (File.Exists(strFileName))
        {
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Open,
                                                            FileAccess.Read,
                                                            FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
                foreach (StoreItem item in items)
                {
                    if(item.ItemNumber == txtItemNumber.Text)
                    {
                        cbxCategories.Text = item.Category;
                        cbxSubCategories.Text = item.SubCategory;
                        txtItemName.Text = item.ItemName;
                        txtUnitPrice.Text = item.UnitPrice.ToString("F");
                    }
                }
            }
        }
        
        strFileName = @"C:\Microsoft Visual C# Application Design\" + txtItemNumber.Text + ".jpg";
    
        if (File.Exists(strFileName))
            pbxSelectedItem.Image = Image.FromFile(strFileName);
        else
            pbxSelectedItem.Image = Image.FromFile(@"C:\Microsoft Visual C# Application Design\MusicItem.jpg");
    }
  3. In the Solution Explorer, double-click NewStoreItem.cs
  4. Double-click an unoccupied area of the form to generate its Load event
  5. Implement the event as follows:
    private void NewStoreItem_Load(object sender, EventArgs e)
    {
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        if (File.Exists(strFileName))
        {
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Open,
                                                            FileAccess.Read,
                                                            FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
                // Display the categories in the combo box
                for(int i = 0; i < items.Count; i++)
                {
                    StoreItem item = (StoreItem)items[i];
    
                    if (!cbxCategories.Items.Contains(item.Category))
                        cbxCategories.Items.Add(item.Category);
                }
            }
        }
    
        strFileName = @"C:\Microsoft Visual C# Application Design\MusicItem.jpg";
    
        if (File.Exists(strFileName))
            pbxSelectedItem.Image = Image.FromFile(strFileName);
    }
  6. Return to the New Store Item form and double-click the Category combo box
  7. Implement the event as follows:
    private void cbxCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        StoreItems<StoreItem> items = new StoreItems<StoreItem>();
        BinaryFormatter bfmStoreItem = new BinaryFormatter();
    
        // This is the file that holds the list of items
        string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
    
        // If the file for the store inventory was created already, ...
        if (File.Exists(strFileName))
        {
            // ... open it
            using (FileStream stmStoreItem = new FileStream(strFileName,
                                                            FileMode.Open,
                                                            FileAccess.Read,
                                                            FileShare.Read))
            {
                // Retrieve the list of items from file
                items = (StoreItems<StoreItem>)bfmStoreItem.Deserialize(stmStoreItem);
    
                // Display the categories in the combo box
                for (int i = 0; i < items.Count; i++)
                {
                    // Get store item based on its index
                    StoreItem item = (StoreItem)items[i];
    
                    // Get the item category
                    if (item.Category == cbxCategories.Text)
                    {
                        // Make sure the category is not yet in the Categories combo box
                        if( !cbxSubCategories.Items.Contains(item.SubCategory) )
                            cbxSubCategories.Items.Add(item.SubCategory);
                    }
                }
            }
        }
    }
  8. Execute the application to test it
  9. Create some records with the following values:
     
    Item # Category Sub-Category Item Name Unit Price
    930485 Keyboards Synthesizers Roland JUNO-Gi Synthesizer 780.00
    485948 Drums Acoustic Drum Sets Sound Percussion Complete 5-Piece Drum Set with Cymbals & Hardware 350.00
    920820 Miscellaneous DJ Accessories Pioneer RMX-1000 Remix Station Black 650.00
    406033 Guitars Electric Guitars B.C. Rich Pro X Custom Special X3 Mockingbird Electric Guitar Tobacco Burst 395.95
    358460 Bass Electric Basses Fender Deluxe P Bass Special 4-String Bass 695.95
    724799 Accessories Cables Monster Cable S-100 XLR Microphone Cable 14.00
    582693 Keyboards Organs Roland VK-88 Combo Organ 5695.00
    350250 Guitars Acoustic Guitars FA-100 Acoustic 120.00
    332085 Miscellaneous Multitrack Recorders Zoom R8 8-Track SD Recorder, Sampler & USB Interface 295.75
    836360 Brass Instruments Trumpets Brasswind Model II Student Bb Trumpet 180.00
    415158 Drums Electronic Drum Sets Simmons SD5X Electronic Drum Set 425.75
    886182 Keyboards Synthesizers Roland Jupiter-80 Synthesizer 3525.00
    516080 Guitars Acoustic-Electric Guitars Taylor 214ce Rosewood/Spruce Grand Auditorium Acoustic-Electric Guitar 1000.00
    536949 Live Sound Packages Phonic Powerpod 620 Plus / S710 PA Package 295.95
    414913 Woodwinds Saxophones Allora Vienna Series Intermediate Alto Saxophone 795.95
    161553 Miscellaneous Multitrack Recorders TASCAM DP-32 Digital 32-Track Portastudio 795.95
    355862 Guitars Electric Guitars PRS SE Custom 24 Electric Guitar 595.85
    293488 Bass Electric Basses Ibanez SR1206E 6-String Electric Bass Vintage 1250.00
    330088 Keyboards Synthesizers Korg MicroKORG Synthesizer/Vocoder 415.55
    115599 Accessories Cables Right-On Cable 98.95
    402882 Accessories Cables Monster Cable Digilink 5 Pin MIDI Cable 9.95
    937528 Guitars Electric Guitars ESP LTD EC-256FM Electric Guitar 395.95
    355582 Miscellaneous Speakers Peavey PR 12 Speaker Pair 360.00
    140864 Brass Instruments Trombones Allora Student Series Bb Trombone Model AATB-102 215.50
    173031 Drums Hi-Hat Cymbals Zildjian ZXT Solid Hi-Hat Cymbal (Pair) 14 Inches 145.75
    217790 Live Sound Microphones MXL 3000 Mic Bundle 245.85
    676184 Keyboards Pianos Williams Overture 88 Key Digital Piano 595.95
    406266 Live Sound Microphones MXL V63M Condenser Studio Microphone 99.95
    357020 Drums Acoustic Drum Sets Ludwig Breakbeats by Questlove 4-Piece Shell Pack Azure Sparkle 395.95
    486021 Keyboards Synthesizers Roland BK-9 Backing Keyboard 2495.85
    686659 Bass Electric Basses Fender American Deluxe Jazz Bass V 5-String Electric Bass 1795.95
    583746 Guitars Acoustic Guitars Yamaha FG700S Folk Acoustic Guitar 225.50
    388835 Drums Acoustic Drum Sets Gretsch Drums Energy 5-Piece Drum Set with Hardware and Sabian SBR Cymbals 695.95
    258395 Accessories Cables Monster Cable Performer 500 Speaker Cable 21.50
    769138 Live Sound Amplifiers Acoustic Lead Guitar Series G120 DSP 120W Guitar Combo Amp 199.95
    275157 Keyboards Synthesizers Yamaha S90XS 88-Key Balanced Weighted Hammer Action Synthesizer 2450.00
    843814 Guitars Acoustic Guitars Fender CD100 12-String Acoustic Guitar Natural 255.50
    281141 Orchestra Violins Florea Recital II Violin Outfit 150.00
    966060 Drums Electronic Drum Sets Simmons SDXpress2 Compact 5-Piece Electronic Drum Kit 225.50
    559606 Live Sound Packages Gear One PA2400 / Kustom KPC15 Mains and Monitors Package 696.95
    725504 Miscellaneous Mixers Nady PMX-1600 16 Channel/4 Bus Powered Mixer w/DSP Effects 649.95
    972405 Guitars Electric Guitars ESP LTD EC-256FM Electric Guitar 395.95
    434426 Keyboards Pianos Suzuki S-350 Mini Grand Digital Piano 2500.00
    259592 Accessories Cables Mogami Gold Instrument Cable Angled - Straight Cable 42.25
    382730 Orchestra Violins Mendini 4/4 MV300 Solid Wood Violin in Satin Finish 59.95
    849926 Bass Electric Basses Squier by Fender Vintage Modified Jazz Bass ''77, Amber 325.50
    207925 Woodwinds Saxophones Yamaha YAS-62III Professional Alto Saxophone 2950.00
  10. Close the forms and return to your programming environment
  11. Execute the application
  12. On the Solo Music Store form, click the Update Store Item button
  13. In the item # text box, type 350250 and press Tab
  14. Change its name to Fender FA-100 Acoustic Guitar
  15. Change its price to 125.75
  16. Click Update Store Item and click Yes
  17. On the Solo Music Store form, click the Update Store Item button
  18. In the item # text box, type 115599 and press Tab
  19. Click Delete Store Item and click Yes
  20. Close the forms and return to your programming environment

Practical LearningPractical Learning: Clearing  a Collection

  1. (You can skip this section)
    1. If necessary, Access the Solo Music Store
    2. Add a button and change its properties as follows:
      (Name): btnDeleteAllStoreItems
      Text: btnDelete all Store Items
    3. Double-click the button and implement its event as follows:
      private void btnDeleteAllStoreItems_Click(object sender, EventArgs e)
      {
          BinaryFormatter bfmStoreItem = new BinaryFormatter();
          StoreItems<StoreItem> items = new StoreItems<StoreItem>();
      
          string strFileName = @"C:\Microsoft Visual C# Application Design\Solo Music Store\StoreItems.slm";
      
          if (MessageBox.Show("Are you sure you want to delete all items?",
                              "Solo Music Store",
                              MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
          {
                      items.Clear();
                      MessageBox.Show("All items have been deleted from the inventory.",
                                      "Solo Music Store",
                                      MessageBoxButtons.OK, MessageBoxIcon.Question);
      
                      lvwAvailableItems.Items.Clear();
                      lbxSubCategories.Items.Clear();
                      lbxCategories.Items.Clear();
      
              if (File.Exists(strFileName))
              {
                  File.Delete(strFileName);
              }
          }
      }

Application

 
 
   
 

Home Copyright © 2014, FunctionX