Home

Collection-Based Application:
College Park Auto-Parts

     

Introduction

The .NET Framerowk provides an impressive series of collection classes. They are organized in various namespaces. The two most common interfaces are System.Collections and System.Collections.Generics. This application is an example of using generic collection classes.

Practical LearningPractical Learning: Introducing the Application

  1. Start Microsoft Visual Studio and create a new Windows Application named CollegeParkAutoParts1
  2. In the Solution Explorer, right-click Form1.cs and click Rename
  3. Type CollegeParkAutoParts.cs and press Enter twice to display the CollegeParkAutoParts form

The Part Description Class

A collection-based application needs a class that would be used to identify each item. For our auto-parts application, we will create a class named PartDescription. Since this is a collection-based application, the class will need to be serializable.

The class will have the following properties:

  • Part Number: This will be a unique number that identifies each item
  • Year: Since each car is manufactured in a specific year, this piece of information will serve that purpose
  • Make: This is the manufacturer of the vehicle
  • Model: This is the model of the vehicle
  • Part Name: This is information that identifies the part
  • Unit Price: This is the basic price to pay for the part

We will use two constructors. The default constructor can be used to create an empty object. Another constructor will use an argument for each property of the class. This will make it possible to create a complete object.

Practical LearningPractical Learning: Creating the Part Description Class

  1. In the Solution Explorer, right-click CollegeParkAutoParts1 -> Add -> Class...
  2. Set the name to PartDescription and press Enter
  3. To create a class that can hold a structured item of a list, change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CollegeParkAutoParts1
    {
        [Serializable]
        public class PartDescription
        {
            public long   PartNumber { get; set; }
            public int    Year       { get; set; }
            public string Make       { get; set; }
            public string Model      { get; set; }
            public string Category   { get; set; }
            public string PartName   { get; set; }
            public double UnitPrice  { get; set; }
    
            public PartDescription()
            {
                PartNumber = 0;
                Year       = 1960;
                Make       = "";
                Model      = "";
                Category   = "";
                PartName   = "Unknown";
                UnitPrice  = 0.00;
            }
    
            public PartDescription(long   code,  int    year, string make,
                                   string model, string type,
                                   string desc,  double UPrice)
            {
                PartNumber = code;
                Year       = year;
                Make       = make;
                Model      = model;
                Category   = type;
                PartName   = desc;
                UnitPrice  = UPrice;
            }
    
            public override string ToString()
            {
                return this.PartNumber + " " +
                       this.Year.ToString() + " " +
                       this.Make + " " +
                       this.Model + " " +
                       this.Category + " " +
                       this.PartName + " " +
                       this.UnitPrice;
            }
        }
    }
  4. Save the file

Parts Ordered

Our auto parts business sells objects. Whenever an object is sold, we must enter its information in an invoice. To keep track of this, we will use a class that resembles that of the part description.

Practical LearningPractical Learning: Creating the Part Ordered Class

  1. In the Solution Explorer, right-click CollegeParkAutoParts1 -> Add -> Class...
  2. Set the name to PartsOrdered and press Enter
  3. To create another class independent for a list, change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CollegeParkAutoParts1
    {
        [Serializable]
        public class PartsOrdered
        {
            public long PartNumber  { get; set; }
            public string PartName  { get; set; }
            public double UnitPrice { get; set; }
            public int Quantity     { get; set; }
            public double SubTotal  { get; set; }
        }
    }
  4. Save the file

Parts Organization

Auto parts are organized from their characteristics such as the vehicle make, the model, and the category. We will need dialog boxes that can assist a user with creating those pieces of information.

Practical LearningPractical Learning: Creating the Parts Accessories

  1. To create a dialog box, on the main menu, click PROJECT -> Add Windows Form...
  2. Set the name to Make and click Add
  3. Design the form as follows:
     
    College Park Auto-Parts - Vehicle Make
    Control Text Name Other Properties
    Label Label &Make:    
    TextBox Label   txtMake Modifiers: Public
    Button Button &OK btnOK DialogResult: OK
    Button Button &Cancel btnCancel DialogResult: Cancel
    Form Property Value
    FormBorderStyle FixedDialog
    Text Make Editor
    StartPosition CenterScreen
    AcceptButton btnOK
    CancelButton btnCancel
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  4. To create a dialog box, on the main menu, click PROJECT -> Add Windows Form...
  5. Set the name to Model and click Add
  6. Design the form as follows:
     
    College Park Auto-Parts - Vehicle Model
    Control Text Name Other Properties
    Label Label &Model:    
    TextBox Label   txtModel Modifiers: Public
    Button Button &OK btnOK DialogResult: OK
    Button Button &Cancel btnCancel DialogResult: Cancel
    Form Property Value
    FormBorderStyle FixedDialog
    Text Model Editor
    StartPosition CenterScreen
    AcceptButton btnOK
    CancelButton btnCancel
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  7. To create a dialog box, in the Solution Explorer, right-click CollegeParkAutoParts1 -> Add -> Windows Form...
  8. Set the name to Category and click Add
  9. Design the form as follows:
     
    College Park Auto Parts - Category
    Control Text Name Other Properties
    Label Label C&ategory:    
    TextBox Label   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
  10. Save all

Part Identification

Probably the most important piece of information about an item sold in a store is its name. When it comes to a business, the second most important piece of information about an item is its cost. When it comes to a database, the most important piece of information about an item is a (unique) number used to identify it. We will create a dialog box that a user can use to create an item sold in the store.

Practical LearningPractical Learning: Creating a Dialog Box for Parts

  1. On the main menu, click PROJECT -> Add Windows Form...
  2. Set the Name to NewStoreItem and click Add
  3. Design the form as follows:
     
    College Park Auto-Part - Part Editor
     
    Control Text Name Other Properties
    Label Label &Year:    
    TextBox Label   txtItemNumber  
    Label Label &Make:    
    ComboBox Combo Box   cbxMakes  
    Button Button New C&ategory... btnNewMake  
    Label Label M&odel:    
    ComboBox Combo Box   cbxModels  
    Button Button New Mo &del... btnNewModel  
    Label Label &Category:    
    ComboBox Combo Box   cbxCategories  
    Button Button New Ca&tegory btnNewCategory  
    Label Label &Unit Price:    
    TextBox Label 0.00 txtUnitPrice TextAlign: Right
    Label Label Part #:    
    TextBox Label   txtPartNumber  
    Label Label &Part Name:    
    TextBox Label   txtPartName  
    Button Button Submit btnSubmit  
    Button Button Close btnClose DialogResult: Cancel
    Form Property Value
    FormBorderStyle FixedDialog
    Text College Park Auto -Parts: Part Editor
    StartPosition CenterScreen
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  4. Double-click the New Make button and implement it as follows:
     private void btnNewMake_Click(object sender, EventArgs e)
    {
        Make editor = new Make();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            if (editor.txtMake.Text.Length > 0)
            {
                string strMake = editor.txtMake.Text;
    
                // Make sure the category is not yet in the list
                if (cbxMakes.Items.Contains(strMake))
                    MessageBox.Show(strMake + " is already in the list.",
                                    "College Park Auto-Parts",
                                 MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    // Since this is a new category, add it to the combo box
                    cbxMakes.Items.Add(strMake);
                }
    
                cbxMakes.Text = strMake;
            }
        }
    }
  5. Return to the New Store Item dialog box and double-click the New Model button
  6. Implement the event as follows:
    private void btnNewModel_Click(object sender, EventArgs e)
    {
        Model editor = new Model();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            if (editor.txtModel.Text.Length > 0)
            {
                string strModel = editor.txtModel.Text;
    
                // Make sure the category is not yet in the list
                if (cbxModels.Items.Contains(strModel))
                    MessageBox.Show(strModel + " is already in the list.",
                                    "College Park Auto-Parts",
                                  MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    // Since this is a new category, add it to the combo box
                    cbxModels.Items.Add(strModel);
                }
    
                cbxModels.Text = strModel;
            }
        }
    }
  7. Return to the New Store Item dialog box and double-click the New Category button
  8. Implement the event as follows:
    private void btnNewCategory_Click(object sender, EventArgs e)
    {
        Category editor = new Category();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            if (editor.txtCategory.Text.Length > 0)
            {
                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.",
                                    "College Park Auto-Parts",
                                 MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    // Since this is a new category, add it to the combo box
                    cbxCategories.Items.Add(strCategory);
                }
                
                cbxCategories.Text = strCategory;
            }
        }
    }
  9. Save all

The Main Form

When this application starts, it will display the main form from where a user can locate and select a part. On the left side of the form, we will create a tree view that displays nodes from which a user can select a car year, a vehicle make, and a model. Then, the user can select a category. This would cause a list view on the right side of the form to display the parts that fit the criteria from the tree view.

Practical LearningPractical Learning: Enumerating a List

  1. Display the CollegeParkAutoParts form
  2. From the Components section of the Toolbox, click ImageList and click the form
  3. In the Properties window, click (Name) and type AutoPartsImages
  4. Click the ellipsis button of the Images field
  5. In the Image Collection Editor, click Add
  6. Locate the folder that contains the resources for these lessons and display it in the Look In combo box
  7. Select the following icons: Sign1, Sign2, Cliper1, Cliper2, Rulers1, Rulers2, Graph1, Graph2, Tool1, and Tool2
  8. Click Open
     
    Image Collection Editor
  9. Click OK
  10. Design the form as follows:
     
    College Park Auto Parts - Form Design
    Control Text Name Other Properties
    Label Label College Park Auto-Parts   Font: Times New Roman, 20.25pt, style=Bold
    ForeColor: Blue
    Panel     Height: 2
    GroupBox GroupBox Part Identification    
    TreeView Tree View   tvwAutoParts ImageList: AutoPartsImages
    GroupBox GroupBox Available Parts    
    ListView ListView   lvwAutoParts FullRowSelect: True
    GridLines: True
    View: Details
    Columns   (Name) Text TextAlign Width
    colPartNumber Part #    
    colPartName Part Name   300
    colUnitPrice Unit Price Right 80
    GroupBox GroupBox Customer Order - Selected Parts    
    Label Label Part #    
    Label Label Part Name    
    Label Label Unit Price    
    Label Label Qty    
    Label Label Sub Total    
    TextBox Text Box   txtPartNumber  
    TextBox Text Box   txtPartName  
    TextBox Text Box 0.00 txtUnitPrice TextAlign: Right
    TextBox Text Box 0 txtQuantity TextAlign: Right
    TextBox Text Box 0.00 txtSubTotal TextAlign: Right
    Button Button Add/Select btnAdd
    ListView List View   lvwSelectedParts FullRowSelect: True
    GridLines: True
    View: Details
    Columns   (Name) Text TextAlign Width
    colPartNumberSelected Part #   45
    colPartNameSelected Part Name   274
    colUnitPriceSelected Unit Price Right 58
    colQuantitySelected Qty Right 28
    colSubTotalSelected Sub-Total Right 58
    GroupBox Group Box Order Summary
    Button Button New Au&to Part... btnNewAutoPart  
    Label Label Receipt #:  
    TextBox Text Box txtSave
    Button Button Save btnSave
    Label Label Tax Rate:
    TextBox Text Box 7.75 txtTaxRate TextAlign: Right
    Label Label %
    Label Label Parts Total:
    TextBox Text Box 0.00 txtPartsTotal TextAlign: Right
    Button Button &New Customer Order btnNewCustomerOrder  
    Label Label Receipt #:  
    TextBox Text Box txtOpen
    Button Button Save btnOpen
    Label Label Tax Amount:
    TextBox Text Box 0.00 txtTaxAmount TextAlign: Right
    Label Label Order Total:
    TextBox Text Box 0.00 txtOrderTotal TextAlign: Right
    Button Button Close btnClose  
  11. Click the Available Parts list view
  12. In the Properties window, click the Events button and, in the Events section, double-click DoubleClick
  13. Implement the event as follows:
    private void lvwAutoParts_DoubleClick(object sender, EventArgs e)
    {
        ListViewItem lviAutoPart = lvwAutoParts.SelectedItems[0];
    
        if ((lvwAutoParts.SelectedItems.Count == 0) ||
            (lvwAutoParts.SelectedItems.Count > 1))
            return;
    
        txtPartNumber.Text = lviAutoPart.Text;
        txtPartName.Text = lviAutoPart.SubItems[1].Text;
        txtUnitPrice.Text = lviAutoPart.SubItems[2].Text;
    
        txtQuantity.Text = "1";
        txtSubTotal.Text = lviAutoPart.SubItems[2].Text;
    
        txtQuantity.Focus();
    }
  14. Return to the College Park Auto-Parts form
  15. Click the Unit Price text box
  16. On the Properties window,  click the Events button Events and double-click Leave
  17. Implement the event as follows:
    private void txtUnitPrice_Leave(object sender, EventArgs e)
    {
        double unitPrice = 0.00D;
        double quantity = 0;
        double subTotal = 0.00D;
    
        try
        {
            unitPrice = double.Parse(txtUnitPrice.Text);
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Unit Price!",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        try
        {
        	quantity = int.Parse(txtQuantity.Text);
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Quandtity!",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        subTotal = unitPrice * quantity;
        txtSubTotal.Text = subTotal.ToString("F");
    }
    
    internal void CalculateOrder()
    {
        // Calculate the current total order and update the order
        double PartsTotal = 0.00D;
        double TaxRate = 0.00D;
        double TaxAmount = 0.00D;
        double OrderTotal = 0.00D;
                
        foreach (ListViewItem lvi in lvwSelectedParts.Items)
        {
            ListViewItem.ListViewSubItem SubItem = lvi.SubItems[4];
            PartsTotal += double.Parse(SubItem.Text);
        }
    
        try
        {
            TaxRate = double.Parse(txtTaxRate.Text) / 100;
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Tax Rate",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        TaxAmount = PartsTotal * TaxRate;
        OrderTotal = PartsTotal + TaxAmount;
    
        txtPartsTotal.Text = PartsTotal.ToString("F");
        txtTaxAmount.Text = TaxAmount.ToString("F");
        txtOrderTotal.Text = OrderTotal.ToString("F");
    }
  18. Return to the College Park Auto-Parts form and click the Qty text box
  19. In the Events section of the Properties, click Leave, then click the arrow of its combo box and select txtUnitPrice_Leave
  20. Return to the College Park Auto-Parts form and click the Selected Parts list view (the list view in the bottom-right section of the form)
  21. In the Events section of the Properties window, double-click DoubleClick
  22. Implement the event as follows:
    private void lvwSelectedParts_DoubleClick(object sender, EventArgs e)
    {
        ListViewItem lviSelectedPart = lvwSelectedParts.SelectedItems[0];
    
        if( (lvwSelectedParts.SelectedItems.Count == 0) ||
            (lvwSelectedParts.SelectedItems.Count > 1) )
            return;
    
        txtPartNumber.Text = lviSelectedPart.Text;
        txtPartName.Text = lviSelectedPart.SubItems[1].Text;
        txtUnitPrice.Text = lviSelectedPart.SubItems[2].Text;
        txtQuantity.Text = lviSelectedPart.SubItems[3].Text;
        txtSubTotal.Text = lviSelectedPart.SubItems[4].Text;
    
        lvwSelectedParts.Items.Remove(lviSelectedPart);
        CalculateOrder();
    }
  23. Save all
 
 
 

Creating a Store Item

The primary operation to be performed on a database is to create an item. For our auto-parts business, this consists of creating an object based on the PartDecription class. When the object has been created, it is added to the collection class. For our application, we will use the List<> class that is defined in the System.Collections.Generics namespace. That class is equipped with all the methods and properties necessary for our collection-based application.

Practical LearningPractical Learning: Adding Items to an ArrayList List

  1. Display the New Store Item form and double-click the Submit button
  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 CollegeParkAutoParts1
    {
        public partial class NewStoreItem : Form
        {
            List<PartDescription> lstAutoParts;
    
            . . . No Change
    
            private void btnSubmit_Click(object sender, EventArgs e)
            {
                FileStream stmAutoParts = null;
                BinaryFormatter bfmAutoParts = new BinaryFormatter();
    
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(@"C:\College Park Auto Parts");
                // This is the file that holds the list of items
                string FileName = @"C:\College Park Auto Parts\Parts.prs";
    
                // Create a random number that will be used to identify the item
                Random rnd = new Random();
                txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
    
                // Make sure the user had selected a make
                if (cbxYears.Text.Length == 0)
                {
                    MessageBox.Show("You must specify the year.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbxYears.Focus();
                    return;
                }
    
                // Make sure the user had selected a make
                if (cbxMakes.Text.Length == 0)
                {
                    MessageBox.Show("You must specify the car name.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbxMakes.Focus();
                    return;
                }
    
                // Make sure the user had selected a model
                if (cbxModels.Text.Length == 0)
                {
                    MessageBox.Show("You must specify the model of the car.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbxModels.Focus();
                    return;
                }
    
                // Make sure the user had selected the part category
                if (cbxCategories.Text.Length == 0)
                {
                    MessageBox.Show("You must specify the part's category.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbxCategories.Focus();
                    return;
                }
    
                // Make sure the user had entered a name/description
                if (txtPartName.Text.Length == 0)
                {
                    MessageBox.Show("You must enter the name (or a " +
                                    "short description) for the part.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtPartName.Focus();
                    return;
                }
    
                // Make sure the user had typed a price for the item
                if (txtUnitPrice.Text.Length == 0)
                {
                    MessageBox.Show("You must enter the price of the item.",
                                    "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtUnitPrice.Focus();
                    return;
                }
    
                // Before saving the new part, find out if there was
                // already a file that holds the list of parts
                // If that file exists, open it and store its parts 
                // in our lstParts variable
                if (File.Exists(FileName))
                {
                    using( stmAutoParts = new FileStream(FileName,
                                                  FileMode.Open,
                                                  FileAccess.Read,
                                                  FileShare.Read) )
                    {
                        // Retrieve the list of items from file
         lstAutoParts = (List<PartDescription>)bfmAutoParts.Deserialize(stmAutoParts);
                    }
                }
    
                // Create the part
                PartDescription part = new PartDescription();
                part.PartNumber = long.Parse(txtPartNumber.Text);
                part.Year = int.Parse(cbxYears.Text);
                part.Make = cbxMakes.Text;
                part.Model = cbxModels.Text;
                part.Category = cbxCategories.Text;
                part.PartName = txtPartName.Text;
                part.UnitPrice = double.Parse(txtUnitPrice.Text);
    
                // Call the Add method of our collection class to add the part
                lstAutoParts.Add(part);
    
                // Save the list
                using( stmAutoParts = new FileStream(FileName,
                       	                         FileMode.Create,
                            	                 FileAccess.Write,
                                    	         FileShare.Write) )
                {
                    bfmAutoParts.Serialize(stmAutoParts, lstAutoParts);
    
                    // After saving the item, reset the form
                    cbxYears.Text = "";
                    cbxMakes.Text = "";
                    cbxModels.Text = "";
                    cbxCategories.Text = "";
                    txtPartName.Text = "";
                    txtUnitPrice.Text = "0.00";
                    txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
                }
            }
        }
    }
  3. In the Solution Explorer, double-click CollegeParkAutoParts.cs and double-click the Save button
  4. Implement its 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 CollegeParkAutoParts1
    {
        public partial class CollegeParkAutoParts : Form
        {
            int iFileName; // This variable will be used later
            List<PartDescription> lstAutoParts;
    
            public CollegeParkAutoParts()
            {
                InitializeComponent();
            }
    
            . . . No Change
                
            private void btnSave_Click(object sender, EventArgs e)
            {
                BinaryFormatter bfmCustomerOrder = new BinaryFormatter();
    
                // We will store our files in the following folder    
                string strDirectory = @"C:\College Park Auto Parts\Receipts";
                DirectoryInfo dirInfo = new DirectoryInfo(strDirectory);
    
                string strFilename = strDirectory + "\\" + txtSave.Text + ".cap";
    
                List<PartsOrdered> lstOrderedParts = null;
    
                if (lvwSelectedParts.Items.Count == 0)
                    return;
                else
                {
                    lstOrderedParts = new List<PartsOrdered>();
    
                    for (int i = 0; i < lvwSelectedParts.Items.Count; i++)
                    {
                        PartsOrdered part = new PartsOrdered();
    
                        part.PartNumber = long.Parse(lvwSelectedParts.Items[i].Text);
                        part.PartName = lvwSelectedParts.Items[i].SubItems[1].Text;
                        part.UnitPrice = double.Parse(lvwSelectedParts.Items[i].SubItems[2].Text);
                        part.Quantity = int.Parse(lvwSelectedParts.Items[i].SubItems[3].Text);
                        part.SubTotal = double.Parse(lvwSelectedParts.Items[i].SubItems[4].Text);
                        lstOrderedParts.Add(part);
                    }
    
                    using (FileStream stmCustomerOrder = new FileStream(strFilename, FileMode.Create))
                    {
                        bfmCustomerOrder.Serialize(stmCustomerOrder, lstOrderedParts);
                        stmCustomerOrder.Close();
                    }
                }
            }
        }
    }
  5. Save all
  6. Display the New Store Item form and double-click the Makes combo box
  7. Implement its SelectedIndexChanged event as follows:
    private void cbxMakes_SelectedIndexChanged(object sender, EventArgs e)
    {
        cbxModels.Text = "";
        cbxModels.Items.Clear();
    
        foreach (PartDescription part in lstAutoParts)
            if (part.Make == cbxMakes.Text)
                if (!cbxModels.Items.Contains(part.Model))
                    cbxModels.Items.Add(part.Model);
    }
  8. Display the College Park Auto-Parts form and double-click the Add/Select button
  9. Implement the event as follows:
    private void btnAdd_Click(object sender, EventArgs e)
    {
        if (txtPartNumber.Text.Length == 0)
        {
            MessageBox.Show("There is no part to be added to the order.",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
    
        foreach (PartDescription part in lstAutoParts)
        {
            if (part.PartNumber == long.Parse(txtPartNumber.Text))
            {
                ListViewItem lviSelectedPart =
    		new ListViewItem(part.PartNumber.ToString());
    
                lviSelectedPart.SubItems.Add(part.PartName);
                lviSelectedPart.SubItems.Add(part.UnitPrice.ToString());
                lviSelectedPart.SubItems.Add(txtQuantity.Text);
                lviSelectedPart.SubItems.Add(txtSubTotal.Text);
                lvwSelectedParts.Items.Add(lviSelectedPart);
            }
        }
    
        CalculateOrder();
    }
  10. Return to the College Partk Auto-Parts form and double-click the Open button
  11. Implement its event as follows:
    private void btnOpen_Click(object sender, EventArgs e)
    {
        List<PartsOrdered> lstReceipts = null;
        BinaryFormatter bfmReceipts = new BinaryFormatter();
        FileStream stmReceipts = null;
    
        string strDirectory = @"C:\College Park Auto Parts\Receipts";
        string strFilename = "";
    
        DirectoryInfo dirReceipts = new DirectoryInfo(strDirectory);
        FileInfo[] fleReceipts = dirReceipts.GetFiles();
    
        if (txtOpen.Text.Length == 0)
        {
            MessageBox.Show("You must enter a receipt number\n" +
                            "There is no receipt number to " +
                            "open a customer's order.",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
            txtOpen.Focus();
            return;
        }
    
        if (fleReceipts.Length == 0)
        {
            MessageBox.Show("There is no customer order to open.",
                            "College Park Auto-Parts",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
            txtOpen.Focus();
            return;
        }
        else
        {
            lvwAutoParts.Items.Clear();
            lvwSelectedParts.Items.Clear();
    
            strFilename = strDirectory + "\\" + txtOpen.Text + ".cap";
    
            if (File.Exists(strFilename))
            {
                using( stmReceipts = new FileStream(strFilename, FileMode.Open) )
                {
               lstReceipts = (List<PartsOrdered>)bfmReceipts.Deserialize(stmReceipts);
    
                    foreach (PartsOrdered part in lstReceipts)
                    {
                        ListViewItem lviReceiptPart =
    			new ListViewItem(part.PartNumber.ToString());
    
                        lviReceiptPart.SubItems.Add(part.PartName);
                        lviReceiptPart.SubItems.Add(part.UnitPrice.ToString());
                        lviReceiptPart.SubItems.Add(part.Quantity.ToString());
                        lviReceiptPart.SubItems.Add(part.SubTotal.ToString());
                        lvwSelectedParts.Items.Add(lviReceiptPart);
                    }
                }
    
                CalculateOrder();
                txtSave.Text = txtOpen.Text;
            }
            else
                MessageBox.Show("There is no customer order with that receipt number.",
    	                    "College Park Auto-Parts",
            	            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
  12. Display the New Store Item form and double-click an unoccupied area of its body
  13. Implement the Load event as follows:
    private void NewStoreItem_Load(object sender, EventArgs e)
    {
        // Since all values seem ready, prepare to process the item
        lstAutoParts = new List<PartDescription>();
        BinaryFormatter bfmAutoParts = new BinaryFormatter();
    
        for (int i = DateTime.Today.Year + 1; i >= 1960; i--)
            cbxYears.Items.Add(i.ToString());
    
        // Create a random number that will be used to identify the item
        Random rnd = new Random();
        txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
    
        // This is the file that holds the list of parts
        string FileName = @"C:\College Park Auto Parts\Parts.prs";
    
        if (File.Exists(FileName))
        {
            using (FileStream stmAutoParts = new FileStream(FileName,
    	                                                FileMode.Open,
            	                	                FileAccess.Read,
                    		                	FileShare.Read))
            {
                // Retrieve the list of items from file
                lstAutoParts = (List<PartDescription>)bfmAutoParts.Deserialize(stmAutoParts);
    
                // Display the car manufacturers in the Make combo box
                foreach (PartDescription part in      lstAutoParts )
                {
                    if (!cbxMakes.Items.Contains(part.Make))
                        cbxMakes.Items.Add(part.Make);
                }
    
                // Display the pats categories in the Category combo box
                foreach (PartDescription part in      lstAutoParts )
                {
                    if (!cbxCategories.Items.Contains(part.Category))
                        cbxCategories.Items.Add(part.Category);
                }
            }
        }
    }
  14. Display the College Park Auto-Parts form and click the Part # text box
  15. In the Events section of the Properties window, double-click Leave and implement the event as follows:
    private void txtPartNumber_Leave(object sender, EventArgs e)
    {
        // We will allow the user to enter a part number
        // In the beginning, we assume that the user 
        // had entered an invalid number
        bool found = false;
        // This will represent the part found, if any
        PartDescription partFound = null;
    
        // After the user had entered a part number,
        // check the whole list of parts
        foreach (PartDescription part in lstAutoParts)
        {
            // If you find a part that holds the number the user had entered
            if( part.PartNumber == long.Parse(txtPartNumber.Text) )
            {
                // Mark that part
                partFound = part;
                // And update the flag that specifies that the part has been found
                found = true;
            }
            // If the part number was not found, check the next
        } // If no part has that number, the found flag keeps marked as false
    
        // If a part with that number was found...
        if (found == true)
        {
            // Show the corresponding part name and unit price
            txtPartName.Text  = partFound.PartName;
            txtUnitPrice.Text = partFound.UnitPrice.ToString("F");
            txtQuantity.Text  = "1";
            txtSubTotal.Text  = partFound.UnitPrice.ToString("F");
            // Give focus to the quantity in case the user was to increase it
            txtQuantity.Focus();
        }
        else
        {
            // Since no part with that number was found,
            // reset the text boxes
            txtPartName.Text = "";
            txtUnitPrice.Text = "0.00";
            txtQuantity.Text = "0";
            txtSubTotal.Text = "0.00";
    
            // Let the user know that the part number that 
            // was entered is not in the list
            MessageBox.Show("There is no part with that number.",
    	                "College Park Auto-Parts",
            	        MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
  16. Return to the College Park Auto-Parts form and double-click the New Auto Part button
  17. Implement the event as follows:
    void ShowAutoParts()
    {
        tvwAutoParts.Nodes.Clear();
        TreeNode nodRoot = tvwAutoParts.Nodes.Add("College Park Auto-Parts",
                                    "College Park Auto-Parts", 0, 1);
        // Show the years nodes
        for (int years = DateTime.Today.Year + 1; years >= 1960; years--)
            nodRoot.Nodes.Add(years.ToString(), years.ToString(), 2, 3);
    
        tvwAutoParts.SelectedNode = nodRoot;
        // Expand the root node
        tvwAutoParts.ExpandAll();
    
        lstAutoParts = new List<PartDescription>();
        BinaryFormatter bfmAutoParts = new BinaryFormatter();
    
        // This is the file that holds the list of auto parts
        string FileName = @"C:\College Park Auto Parts\Parts.prs";
    
        if (File.Exists(FileName))
        {
            using (FileStream stmAutoParts = new FileStream(FileName,
                                                    FileMode.Open,
                                                    FileAccess.Read,
                                                    FileShare.Read))
            {
                // Retrieve the list of parts from file
                lstAutoParts = (List<PartDescription>)bfmAutoParts.Deserialize(stmAutoParts);
    
                // Show the makes nodes
                foreach (TreeNode nodYear in nodRoot.Nodes)
                {
                    List<string> lstMakes = new List<string>();
    
                    foreach (PartDescription part in lstAutoParts)
                    {
                        if (nodYear.Text == part.Year.ToString())
                        {
                            if (!lstMakes.Contains(part.Make))
                                lstMakes.Add(part.Make);
                        }
                    }
    
                    foreach (string strMake in lstMakes)
                        nodYear.Nodes.Add(strMake, strMake, 4, 5);
                }
    
                // Showing the models nodes
                foreach (TreeNode nodYear in nodRoot.Nodes)
                {
                    foreach (TreeNode nodMake in nodYear.Nodes)
                    {
                        List<string> lstModels = new List<string>();
    
                        foreach (PartDescription part in lstAutoParts)
                        {
    
                            if ((nodYear.Text == part.Year.ToString()) &&
                                (nodMake.Text == part.Make))
                            {
                                if (!lstModels.Contains(part.Model))
                                    lstModels.Add(part.Model);
    
                            }
                        }
    
                        foreach (string strModel in lstModels)
                            nodMake.Nodes.Add(strModel, strModel, 6, 7);
                    }
                }
    
                // Showing the categories nodes
                foreach (TreeNode nodYear in nodRoot.Nodes)
                {
                    foreach (TreeNode nodMake in nodYear.Nodes)
                    {
                        foreach (TreeNode nodModel in nodMake.Nodes)
                        {
                            List<string> lstCategories = new List<string>();
    
                            foreach (PartDescription part in lstAutoParts)
                            {
    
                                if ((nodYear.Text == part.Year.ToString()) &&
                                    (nodMake.Text == part.Make) &&
                                    (nodModel.Text == part.Model))
                                {
                                    if (!lstCategories.Contains(part.Category))
                                        lstCategories.Add(part.Category);
                                }
                            }
    
                            foreach (string strCategory in lstCategories)
                                nodModel.Nodes.Add(strCategory,
                            strCategory, 8, 9);
                        }
                    }
                }
            }
        }
    }
    
    private void btnNewAutoPart_Click(object sender, EventArgs e)
    {
        NewStoreItem editor = new NewStoreItem();
    
        if (editor.ShowDialog() == DialogResult.Cancel)
            ShowAutoParts();
    }
  18. Return to the College Park Auto-Parts form and double- click the New Customer Order button
  19. Implement the event as follows:
    private void btnNewCustomerOrder_Click(object sender, EventArgs e)
    {
        // We will store our files in the following folder    
        string strDirectory = @"C:\College Park Auto Parts\Receipts";
        DirectoryInfo dirInfo = Directory.CreateDirectory(strDirectory);
    
        // Get the list of files, if any, from our directory
        FileInfo[] fleList = dirInfo.GetFiles();
    
        // If there is no file in the directory,
        // then we will use 1000 as the first file name
        if (fleList.Length == 0)
        {
            iFileName = 1000;
        }
        else // If there was at least one file in the directory
        {
            // Get a reference to the last file
            FileInfo fleLast = fleList[fleList.Length - 1];
            // Get the name of the last file without its extension
            string fwe = Path.GetFileNameWithoutExtension(fleLast.FullName);
            // Increment the name of the file by 1
            iFileName = int.Parse(fwe) + 1;
        }
    
        txtSave.Text = iFileName.ToString();
    
        lvwAutoParts.Items.Clear();
        lvwSelectedParts.Items.Clear();
    }
  20. Return to the College Park Auto-Parts form and double-click an unoccupied area of its body
  21. Define a new method and implement the Load event as follows:
    private void Central_Load(object sender, EventArgs e)
    {
        ShowAutoParts();
        btnNewCustomerOrder_Click(sender, e);
    }
  22. Return to the College Park Auto-Parts form and click the tree view
  23. In the Events section of the Properties window, double-click NodeMouseClick
  24. Implement the event as follows:
    private void tvwAutoParts_NodeMouseClick(object sender,
    			TreeNodeMouseClickEventArgs e)
    {
        TreeNode nodClicked = e.Node;
    
        if (nodClicked.Level == 4)
            lvwAutoParts.Items.Clear();
    
        try
        {
            foreach (PartDescription part in lstAutoParts)
            {
                if ((part.Category == nodClicked.Text) &&
                    (part.Model == nodClicked.Parent.Text) &&
                    (part.Make == nodClicked.Parent.Parent.Text) &&
                    (part.Year.ToString() == nodClicked.Parent.Parent.Parent.Text))
                {
                    ListViewItem lviAutoPart =
    			new ListViewItem(part.PartNumber.ToString());
    
                    lviAutoPart.SubItems.Add(part.PartName);
                    lviAutoPart.SubItems.Add(part.UnitPrice.ToString("F"));
                    lvwAutoParts.Items.Add(lviAutoPart);
                }
            }
        }
        catch (NullReferenceException)
        {
        }
    }
  25. Return to the College Park Auto-Parts form and double-click the Close button
  26. Implement the event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  27. Execute the application
  28. Click the New Auto Part button and use the Part Editor to create a few parts (let the computer generate the part numbers)
     
  29. Close the Part Editor
  30. Create a few customer part orders and save them:
     
    College Park Auto Parts: Customer Order
     
    College Park Auto Parts: Part Selection
  31. Close the forms and return to your programming environment
  32. Execute the application again and open a previously saved order
  33. Close the forms and return to your programming environment

Application

 
 
   
 

Home Copyright © 2014, FunctionX