Home

Data Set Example Application: College Park Auto-Parts

     

Introduction

This exercise allows you to explore the tables of a data set to create a file-based (or XML-based application.

 

Practical Learning: Introducing Data Sets

  1. Start Microsoft Visual Studio and create a new Windows Forms Application named CollegeParkAutoParts2
  2. To create an icon, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> New Item...
  3. In the Templates list, click Icon File
  4. Set the Name to cpap1 and click Add
  5. Right-click the white area and click Delete Image Type
  6. Design the 16x16, 16 colors version of the icon as follows:
     
  7. On the main menu, click File -> Save cpap1.ico As
  8. Select the bin\Debug folder of the current folder and click Save
  9. On the main menu, click File -> Close
  10. In the Solution Explorer, expand bin and expand Debug
  11. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  12. In the Templates list, make sure Icon File is selected.
    Set the Name to cpap2 and click Add
  13. Right-click the white area and click Delete Image Type
  14. Design the 16x16, 16 colors version of the icon as follows:
     
  15. Save the file and close the icon window
  16. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  17. In the Templates list, make sure Icon File is selected.
    Set the Name to year1 and click Add
  18. Right-click the white area and click Delete Image Type
  19. Design the 16x16, 16 colors version of the icon as follows:
     
  20. Save the file and close the icon window
  21. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  22. In the Templates list, make sure Icon File is selected.
    Set the Name to year2 and click Add
  23. Right-click the white area and click Delete Image Type
  24. Design the 16x16, 16 colors version of the icon as follows:
     
  25. Save the file and close the icon window
  26. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  27. In the Templates list, make sure Icon File is selected.
    Set the Name to make1 and click Add
  28. Right-click the white area and click Delete Image Type
  29. Design the 16x16, 16 colors version of the icon as follows:
     
    Icon Design: Diamond
  30. Save the file and close the icon window
  31. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  32. In the Templates list, make sure Icon File is selected.
    Set the Name to make2 and click Add
  33. Right-click the white area and click Delete Image Type
  34. Design the 16x16, 16 colors version of the icon as follows:
     
    Icon Design: Diamond
  35. Save the file and close the icon window
  36. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  37. In the Templates list, make sure Icon File is selected.
    Set the Name to model1 and click Add
  38. Right-click the white area and click Delete Image Type
  39. Design the 16x16, 16 colors version of the icon as follows:
     
  40. Save the file and close the icon window
  41. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  42. In the Templates list, make sure Icon File is selected.
    Set the Name to model2 and click Add
  43. Right-click the white area and click Delete Image Type
  44. Design the 16x16, 16 colors version of the icon as follows:
     
  45. Save the file and close the icon window
  46. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  47. In the Templates list, make sure Icon File is selected.
    Set the Name to category1 and click Add
  48. Right-click the white area and click Delete Image Type
  49. Design the 16x16, 16 colors version of the icon as follows:
     
  50. Save the file and close the icon window
  51. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
  52. In the Templates list, make sure Icon File is selected.
    Set the Name to category2 and click Add
  53. Right-click the white area and click Delete Image Type
  54. Design the 16x16, 16 colors version of the icon as follows:
     
    Icon Design: Minus
  55. Save the file and close the icon window
  56. In the Solution Explorer, right-click Form1.cs and click Rename
  57. Type Central.cs and press Enter twice to display the Central form
  58. From the Components section of the Toolbox, click ImageList and click the form
  59. In the Properties window, click (Name) and type imgAutoParts
  60. Click the ellipsis button of the Images field
  61. In the Image Collection Editor, click Add
  62. Locate the folder that contains the icons you created and display it in the Look In combo box
  63. Select cpap1.ico and click Open
  64. In the same way, add the other pictures in the following order: cpap2.ico, year1.ico, year2.ico, make1.ico, make2.ico, model1.ico, model2.ico, category1.ico, and category1.ico
     
    Image Collection Editor
  65. Click OK
  66. 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 TreeView   tvwAutoParts ImageList: imgAutoParts
    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 TextBox   txtPartNumber  
    TextBox TextBox   txtPartName  
    TextBox TextBox 0.00 txtUnitPrice TextAlign: Right
    TextBox TextBox 0 txtQuantity TextAlign: Right
    TextBox TextBox 0.00 txtSubTotal TextAlign: Right
    Button Button Add/Select btnAdd
    ListView ListView   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 GroupBox Order Summary
    Button Button New Au&to Part... btnNewAutoPart  
    Label Label Receipt #:  
    TextBox TextBox txtSave
    Button Button Save btnSave
    Label Label Tax Rate:
    TextBox TextBox 7.75 txtTaxRate TextAlign: Right
    Label Label %
    Label Label Parts Total:
    TextBox TextBox 0.00 txtPartsTotal TextAlign: Right
    Button Button &New Customer Order btnNewCustomerOrder  
    Label Label Receipt #:  
    TextBox TextBox txtOpen
    Button Button Save btnOpen
    Label Label Tax Amount:
    TextBox TextBox 0.00 txtTaxAmount TextAlign: Right
    Label Label Order Total:
    TextBox TextBox 0.00 txtOrderTotal TextAlign: Right
    Button Button Close btnClose  
  67. Click the Available Parts list view
  68. In the Properties window, click the Events button and, in the Events section, double-click DoubleClick
  69. 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();
    }
  70. Return to the Central form
  71. Click the Unit Price text box and, in the Events section of the Properties window, double-click Leave
  72. Implement the event as follows:
    private void txtUnitPrice_Leave(object sender, EventArgs e)
    {
        double UnitPrice = 0.00D;
        int Quantity = 0;
        double SubTotal = 0.00D;
    
        try
        {
            UnitPrice = double.Parse(txtUnitPrice.Text);
        }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Unit Price!");
        }
    
        try { Quantity = int.Parse(txtQuantity.Text); }
        catch (FormatException)
        {
            MessageBox.Show("Invalid Quandtity!");
        }
    
        SubTotal = UnitPrice * Quantity;
        txtSubTotal.Text = SubTotal.ToString("F");
    }
    
    internal void CalculateOrder()
    {
        // Calculate the current total order and update the order
        double PartsTotal = 0.00;
        double TaxRate = 0.00;
        double TaxAmount = 0.00;
        double OrderTotal = 0.00;
    
        ListViewItem lviSelectedPart = lvwSelectedParts.Items[0];
    
        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");
        }
    
        TaxAmount = PartsTotal * TaxRate;
        OrderTotal = PartsTotal + TaxAmount;
    
        txtOrderTotal.Text = PartsTotal.ToString("F");
        txtTaxAmount.Text = TaxAmount.ToString("F");
        txtOrderTotal.Text = OrderTotal.ToString("F");
    }
  73. Return to the Central form and click the Qty text box
  74. In the Events section of the Properties, click Leave, then click the arrow of its combo box and select txtUnitPrice_Leave
  75. On the Central form, click the Selected Part list view (the list view in the bottom-right section of the form)
  76. In the Events section of the Properties window, double-click DoubleClick
  77. 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();
    }
  78. To create a dialog box, on the main menu, click Project -> Add Windows Form...
  79. Set the name to ItemsCategories and click Add
  80. From the Data section of the Toolbox, click DataSet and click the form
  81. On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
  82. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Categories
    (Name): dsCategories
  83. Click the Tables field and click its ellipsis button
  84. In the Tables Collection Editor, click Add
  85. In the Properties list, change the characteristics of the table as follows:
    TableName: Category
    (Name): tblCategory
  86. Click Columns and click its ellipsis button
  87. In the Columns Collection Editor, click Add
  88. Change the characteristics of the columns as follows:
    ColumnName: CategoryName
    (Name): colCategoryName 
  89. Click Close and click Close
  90. Design the form as follows:
     
    College Park Auto-Parts: Categories
    Control Text Name Additional Properties
    DataGridView   dgvStudents Anchor: Top, Bottom, Left, Right
    DataSource: dsCategories
    DataMember: Category
    Button Close btnClose Anchor: Bottom, Right
  91. To create a dialog box, on the main menu, click Project -> Add Windows Form...
  92. Set the name to CarMakes and click Add
  93. From the Data section of the Toolbox, click DataSet and click the form
  94. On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
  95. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Makes
    (Name): dsMakes
  96. Click the Tables field and click its ellipsis button
  97. In the Tables Collection Editor, click Add
  98. In the Properties list, change the characteristics of the table as follows:
    TableName: Make
    (Name): tblMake
  99. Click Columns and click its ellipsis button
  100. In the Columns Collection Editor, click Add
  101. Change the characteristics of the columns as follows:
    ColumnName: MakeName
    (Name): colMakeName 
  102. Click Close and click Close
  103. Design the form as follows:
     
    College Park Auto-Parts: Makes
    Control Text Name Additional Properties
    DataGridView   dgvStudents Anchor: Top, Bottom, Left, Right
    DataSource: dsMakes
    DataMember: Makes
    Button Close btnClose Anchor: Bottom, Right
  104. To create a dialog box, on the main menu, click Project -> Add Windows Form...
  105. Set the name to CarModels and click Add
  106. Display the list of makes form
  107. Right-click dsMakes and click Copy
  108. Display the list of models form
  109. Right-click its body and click Paste
  110. From the Data section of the Toolbox, click DataSet and click the form
  111. On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
  112. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Models
    (Name): dsModels
  113. Click the Tables field and click its ellipsis button
  114. In the Tables Collection Editor, click Add
  115. In the Properties list, change the characteristics of the table as follows:
    TableName: Car
    (Name): tblCar
  116. Click Columns and click its ellipsis button
  117. In the Columns Collection Editor, click Add
  118. Change the characteristics of the columns as follows:
    ColumnName: Make
    (Name): colMake
  119. In the Columns Collection Editor, click Add
  120. Change the characteristics of the columns as follows:
    ColumnName: Model
    (Name): colModel
  121. Click Close and click Close
  122. From the Data section of the Toolbox, click DataGridView and click the form
  123. In the Properties window, change its characteristics as follows:
    DataSource: dsModels
    DataMember: Models
  124. Under the Properties window, click Edit Columns... and change the columns as follows:
     
    		
    Selected Columns: HeaderText DataPropertyName ColumnType DataSource DisplayMember
    Make Make Make DataGridViewComboBoxColumn dsMakes Make.MakeName
    Model Model Model      
  125. Click OK
  126. Design the form as follows:
     
    College Partk Auto Parts: Models
    Control Text Name Additional Properties
    DataGridView   dgvStudents Anchor: Top, Bottom, Left, Right
    Button Close btnClose Anchor: Bottom, Right
  127. To create a new form, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> Windows Form...
  128. Set the Name to AutoParts and click Add
  129. Display the list of models form
  130. Click dsMakes
  131. Press and hold Shift
  132. Click dsModels
  133. Release Shift 
  134. Press Ctrl + C
  135. Display the auto parts form
  136. Right-click its body and click Paste
  137. Display the list of categories form
  138. Right-click dsCategories and click Copy
  139. Display the auto parts form
  140. Right-click its body and click Paste
  141. From the Data section of the Toolbox, click DataSet and click the form
  142. In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
  143. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: StoreItems
    (Name): dsStoreItems
  144. Click Tables and click its ellipsis button
  145. In the Properties list, change the characteristics of the table as follows:
    TableName: StoreItem
    (Name): tblStoreItem
  146. Click Columns and click its ellipsis button
  147. In the Columns Collection Editor, click Add continuously and create the columns as follows:
     
    ColumnName (Name)
    PartNumber colPartNumber
    Year colYear
    Make colMake
    Model colModel
    Category colCategory
    PartName colPartName
    UnitPrice colUnitPrice
  148. Click Close and click Close
  149. From the Data section of the Toolbox, click DataGridView and click the form
  150. In the Properties window, change its characteristics as follows:
    DataSource: dsStoreItems
    DataMember: StoreItems
  151. Under the Properties window, click Edit Columns... and change the columns as follows:
     
    		
    Selected Columns: HeaderText DataPropertyName ColumnType DataSource DisplayMember Width
    Part # Part # PartNumber       50
    Year Year Year       40
    Make Make Make DataGridViewComboBoxColumn dsMakes Make.MakeName 85
    Model Model Model DataGridViewComboBoxColumn dsModels CarModel.Model 130
    Category Category Category DataGridViewComboBoxColumn dsCategories Category.CategoryName 120
    Part Name Part Name PartName       185
    Unit Price Unit Price UnitPrice       65
  152. Click OK
  153. Design the form as follows:
     
    College Park Auto Parts: Store Items
     
    Control Text Name Other Properties
    DataGridView   dgvStoreItems DataSource: dsStoreItems
    DataMember: AutoPart
    Anchor: Top, Bottom, Left, Right
    Button New Make... btnNewMake Anchor: Bottom, Left
    Button New Model... btnNewModel Anchor: Bottom, Left
    Button New Category... btnNewCategory Anchor: Bottom, Left
    Button Close btnClose Anchor: Bottom, Right
  154. Double-click the New Make button and implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    
    namespace CollegeParkAutoParts2
    {
        public partial class AutoParts : Form
        {
            public AutoParts()
            {
                InitializeComponent();
            }
    
            private void btnNewMake_Click(object sender, EventArgs e)
            {
                CarMakes frmMakes = new CarMakes();
                frmMakes.ShowDialog();
            }
        }
    }
    
  155. Return to the Part Editor dialog box and double-click the New Model button
  156. Implement the event as follows:
    private void btnNewModel_Click(object sender, EventArgs e)
    {
        CarModels frmModels = new CarModels();
        frmModels.ShowDialog();
    }
  157. Return to the Part Editor dialog box and double-click the New Category button
  158. Implement the event as follows:
    private void btnNewCategory_Click(object sender, EventArgs e)
    {
        ItemsCategories frmCategories = new ItemsCategories();
        frmCategories.ShowDialog();
    }
  159. Display the Central form and double-click the New Auto Part button
  160. Implement its event as follows:
    internal void ShowAutoParts()
    {
    }
    
    private void btnNewAutoPart_Click(object sender, EventArgs e)
    {
        AutoParts frmParts = new AutoParts();
                
        if (frmParts.ShowDialog() == DialogResult.Cancel)
            ShowAutoParts();
    }
  161. Execute the application to make sure everything is working fine
     
    College Park Auto Parts
  162. Close the form(s) and return to your programming environment

Practical LearningPractical Learning: Saving the Records of a Data Set

  1. Display the ItemsCategories form and double-click the Close 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;
    
    namespace CollegeParkAutoParts2
    {
        public partial class ItemsCategories : Form
        {
            public ListOfCategories()
            {
                InitializeComponent();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(strDirectory);
    
                dsCategories.WriteXml(strDirectory + "\\categories.xml");
                Close();
            }
        }
    }
  3. Display the CarMakes form and double-click the Close button
  4. 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;
    
    namespace CollegeParkAutoParts2
    {
        public partial class CarMakes : Form
        {
            public ListOfMakes()
            {
                InitializeComponent();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(strDirectory);
    
                dsMakes.WriteXml(strDirectory + "\\makes.xml");
                Close();
            }
        }
    }
  5. Display the Models form and double-click the Close button
  6. 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;
    
    namespace CollegeParkAutoParts2
    {
        public partial class CarModels : Form
        {
            public ListOfModels()
            {
                InitializeComponent();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(strDirectory);
    
                dsModels.WriteXml(strDirectory + "\\models.xml");
                Close();
            }
        }
    }
  7. Display the Auto Parts form and double-click the Close button
  8. Implement its event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        string strDirectory = @"C:\College Park Auto Parts";
        // If this directory doesn't exist, create it
        Directory.CreateDirectory(strDirectory);
    
        dsStoreItems.WriteXml(strDirectory + "\\StoreItems.xml");
        Close();
    }
  9. Save all

Practical LearningPractical Learning: Opening the Records for a Data Set

  1. Display the ItemsCategories form and double-click an unoccupied area of its body
  2. Implement the event as follows:
    private void ItemsCategories_Load(object sender, EventArgs e)
    {
        string Filename = @"C:\College Park Auto Parts\categories.xml";
    
        if (File.Exists(Filename))
            dsCategories.ReadXml(Filename);
    }
  3. Display the CarMakes form and double-click an unoccupied area of its body
  4. Implement the event as follows:
    private void CarMakes_Load(object sender, EventArgs e)
    {
        string Filename = @"C:\College Park Auto Parts\makes.xml";
    
        if (File.Exists(Filename))
            dsMakes.ReadXml(Filename);
    }
  5. Display the CarModels form and double-click an unoccupied area of its body
  6. Implement the event as follows:
    private void CarModels_Load(object sender, EventArgs e)
    {
        string Filename = @"C:\College Park Auto Parts\makes.xml";
    
        if (File.Exists(Filename))
            dsMakes.ReadXml(Filename); 
                
        Filename = @"C:\College Park Auto Parts\models.xml";
        if (File.Exists(Filename))
            dsModels.ReadXml(Filename);
    }
  7. Display the AutoParts form and double-click an unoccupied area of its body
  8. Implement the event as follows:
    private void AutoParts_Load(object sender, EventArgs e)
    {
        string Filename = @"C:\College Park Auto Parts\StoreItems.xml";
    
        if( File.Exists(Filename) )
            dsStoreItems.ReadXml(Filename);
    }
  9. Return to the form and, in the Properties window, click the Events button
  10. In the Events section of the Properties window, double-click Activated and implement the event as follows:
    private void AutoParts_Activated(object sender, EventArgs e)
    {
        string Filename = @"C:\College Park Auto Parts\makes.xml";
                
        if (File.Exists(Filename))
            dsMakes.ReadXml(Filename);
    
        Filename = @"C:\College Park Auto Parts\models.xml";
    
        if (File.Exists(Filename))
            dsModels.ReadXml(Filename);
    
        Filename = @"C:\College Park Auto Parts\categories.xml";
    
        if (File.Exists(Filename))
            dsCategories.ReadXml(Filename);
    }
  11. Execute the application
  12. Click the New Auto Part button and click the New Make button
  13. Create a few makes as follows:
     
    Ford
    Dodge
    Toyota
    Honda
  14. Click the New Model button and create a few models as follows:
     
    Ford Escort SE L4 2.0
    Dodge Caravan SE L4 2.4
    Toyota Rav4 2WD/4-Door
    Honda Civic 1.7 EX 4DR
    Ford Taurus LX V6 3.0
    Honda Accord 2.3 LX 4DR
  15. Click the New Category button and create a few categories as follows:
     
    Exhaust
    Air Intake
    Fuel Injection
    Cooling System
    Engine Electrical
  16. Close the form(s) and return to your programming environment

Practical LearningPractical Learning: Getting the Values of a Data Set

  1. In the Solution Explorer, Double-click Central.cs
  2. From the Data section of the Toolbox, click DataSet and click the form
  3. In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
  4. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: StoreItems
    (Name): dsStoreItems
  5. Click Tables and click its ellipsis button
  6. In the Properties list, change the characteristics of the table as follows:
    TableName: AutoPart
    (Name): tblAutoPart
  7. Click Columns and click its ellipsis button
  8. In the Columns Collection Editor, click Add continuously and create the columns as follows:
     
    ColumnName (Name)
    PartNumber colPartNumber
    Year colYear
    Make colMake
    Model colModel
    Category colCategory
    PartName colPartName
    UnitPrice colUnitPrice
  9. Click Close and click Close
  10. Right-click the form and click View Code
  11. Change the ShowAutoParts method as follows:
    internal 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();
    
        // This is the file that holds the list of store items on sale
        string Filename = @"C:\College Park Auto Parts\StoreItems.xml";
    
        if (File.Exists(Filename))
        {
            dsStoreItems.ReadXml(Filename);
    
            // Add the makes to the years
            foreach (TreeNode nodYear in nodRoot.Nodes)
            {
                List<string> lstMakes = new List<string>();
    
                foreach (DataRow row in tblAutoPart.Rows)
                {
                    if (nodYear.Text == row["Year"].ToString())
                    {
                        if (!lstMakes.Contains(row["Make"].ToString()))
                            lstMakes.Add(row["Make"].ToString());
                    }
                }
    
                foreach (string strMake in lstMakes)
                    nodYear.Nodes.Add(strMake, strMake, 4, 5);
            }
    
            // Add the models to the makes
            foreach (TreeNode nodYear in nodRoot.Nodes)
            {
                foreach (TreeNode nodMake in nodYear.Nodes)
                {
                    List<string> lstModels = new List<string>();
    
                    foreach (DataRow row in tblAutoPart.Rows)
                    {
                        if ((nodYear.Text == row["Year"].ToString()) &&
                            (nodMake.Text == row["Make"].ToString()))
                        {
                            if (!lstModels.Contains(row["Model"].ToString()))
                                lstModels.Add(row["Model"].ToString());
                        }
                    }
    
                    foreach (string strModel in lstModels)
                        nodMake.Nodes.Add(strModel, strModel, 6, 7);
                }
            }
    
            // Show 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 (DataRow row in tblAutoPart.Rows)
                        {
                            if ((nodYear.Text == row["Year"].ToString()) &&
                                (nodMake.Text == row["Make"].ToString()) &&
                                (nodModel.Text == row["Model"].ToString()))
                            {
                              if (!lstCategories.Contains(row["Category"].ToString()))
                                    lstCategories.Add(row["Category"].ToString());
                            }
                        }
    
                        foreach (string strCategory in lstCategories)
                            nodModel.Nodes.Add(strCategory, strCategory, 8, 9);
                    }
                }
            }
        }
    }
  12. Return to the form and double-click an unoccupied area of its body to generate its Load event
  13. Implement the event as follows:
    private void Central_Load(object sender, EventArgs e)
    {
        ShowAutoParts();
    }
  14. Return to the Central 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)
    {
        foreach (DataRow row in tblAutoPart.Rows)
        {
            if (row["PartNumber"].ToString() == txtPartNumber.Text)
            {
                txtPartName.Text = row["PartName"].ToString();
                txtUnitPrice.Text = row["UnitPrice"].ToString();
                txtQuantity.Text = "0";
                txtSubTotal.Text = "0.00";
            }
        }
    }
  16. Return to the Central form and double-click the Add/Select button
  17. 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");
            return;
        }
    
        ListViewItem lviSelectedPart =
                    new ListViewItem(txtPartNumber.Text);
    
        lviSelectedPart.SubItems.Add(txtPartName.Text);
        lviSelectedPart.SubItems.Add(txtUnitPrice.Text);
        lviSelectedPart.SubItems.Add(txtQuantity.Text);
        lviSelectedPart.SubItems.Add(txtSubTotal.Text);
        lvwSelectedParts.Items.Add(lviSelectedPart);
    
        CalculateOrder();
    }
  18. Scroll up in the file and add the following namespaces:
    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.Xml;
    
    namespace CollegeParkAutoParts2
  19. Return to the Central form and double-click the New Customer Order button
  20. Implement the event as follows:
    private void btnNewCustomerOrder_Click(object sender, EventArgs e)
    {
        int ReceiptNumber = 0;
        string Filename = @"C:\College Park Auto Parts\receipts.xml";
        XmlDocument DOMReceipts = new XmlDocument();
    
        if (File.Exists(Filename))
        {
            DOMReceipts.Load(Filename);
            XmlElement RootReceipts = DOMReceipts.DocumentElement;
    
            XmlNodeList ListOfReceiptNumbers =
    		RootReceipts.GetElementsByTagName("ReceiptNumber");
            ReceiptNumber = int.Parse(ListOfReceiptNumbers[
    		ListOfReceiptNumbers.Count - 1].InnerText);
        }
    
        txtSave.Text = (ReceiptNumber + 1).ToString();
        txtTaxRate.Text = "5.75";
        txtTaxAmount.Text = "0.00";
        txtPartsTotal.Text = "0.00";
        txtOrderTotal.Text = "0.00";
        lvwSelectedParts.Items.Clear();
    }
  21. Return to the Central form and click the tree view
  22. In the Properties window, click the Events button and, in the Events section, double-click NodeMouseClick
  23. 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 (DataRow row in tblAutoPart.Rows)
            {
                if ((row["Category"].ToString() == nodClicked.Text) &&
                    (row["Model"].ToString() == nodClicked.Parent.Text) &&
                    (row["Make"].ToString() == nodClicked.Parent.Parent.Text) &&
                    (row["Year"].ToString() == nodClicked.Parent.Parent.Parent.Text))
                {
                    ListViewItem lviAutoPart =
                        new ListViewItem(row["PartNumber"].ToString());
    
                    lviAutoPart.SubItems.Add(row["PartName"].ToString());
                    lviAutoPart.SubItems.Add(row["UnitPrice"].ToString());
                    lvwAutoParts.Items.Add(lviAutoPart);
                }
            }
        }
        catch (NullReferenceException)
        {
        }
    }
  24. Return to the Central form and double-click the Save button
  25. Implement its event as follows:
    private void btnSave_Click(object sender, EventArgs e)
    {
        // This is the file that holds the receipts
        string Filename = @"C:\College Park Auto Parts\receipts.xml";
        // Get a reference to the root
        XmlDocument DOMReceipts = new XmlDocument();
    
        // We will create a list of all the parts 
        // that the customer wants to purchase
        string strParts = "";
    
        foreach (ListViewItem lviPart in lvwSelectedParts.Items)
        {
            strParts = strParts + "<Part>";
            strParts = strParts + "<PartNumber>" +
                       lviPart.SubItems[0].Text + "</PartNumber>";
            strParts = strParts + "<PartName>" +
                       lviPart.SubItems[1].Text + "</PartName>";
            strParts = strParts + "<UnitPrice>" +
                       lviPart.SubItems[2].Text + "</UnitPrice>";
            strParts = strParts + "<Quantity>" +
                       lviPart.SubItems[3].Text + "</Quantity>";
            strParts = strParts + "<SubTotal>" +
                       lviPart.SubItems[4].Text + "</SubTotal>";
            strParts = strParts + "</Part>";
        }
    
        // If this is the first customer order, ...
        if (!File.Exists(Filename))
        {
            // If this is the first receipt to be created,
            // set the receipt number to 1
            // and create the structure of the document
            DOMReceipts.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                "<CustomersOrders>" +
                                "<Receipt>" +
                                "<ReceiptNumber>1</ReceiptNumber>" + strParts +
                                "<PartsTotal>" + txtPartsTotal.Text +
                                "</PartsTotal><TaxRate>" + txtTaxRate.Text +
                                "</TaxRate><TaxAmount>" + txtTaxAmount.Text +
                                "</TaxAmount><OrderTotal>" + txtOrderTotal.Text +
                                "</OrderTotal></Receipt></CustomersOrders>");
    
            // Save the XML file
            DOMReceipts.Save(Filename);
    
            // Reset the customer order
            txtSave.Text = "2";
            txtOpen.Text = "1";
            txtTaxRate.Text = "5.75";
            txtTaxAmount.Text = "0.00";
            txtPartsTotal.Text = "0.00";
            txtOrderTotal.Text = "0.00";
            lvwSelectedParts.Items.Clear();
        } // If this is not the first customer order, ...
        else // if (File.Exists(Filename))
        {
            XmlNode NodeCustomerOrder = null;
            // We will use a receipt number for each receipt
            int ReceiptNumber = int.Parse(txtSave.Text);
    
            // If at least one receipt had previously been created,
            // then open the XML file that holds the receipts
    
            // Store the XML file structure into the DOM
            DOMReceipts.Load(Filename);
            // Get a reference to the root element
            XmlElement RootCustomersOrders = DOMReceipts.DocumentElement;
    
            // Get a list of the receipt numbers
            XmlNodeList ListOfReceipts = 
    	    RootCustomersOrders.GetElementsByTagName("Receipt");
    
            // Check each receipt
            foreach (XmlNode NodeCurrentReceipt in ListOfReceipts)
            {
                // Look for a receipt that has the same number
                // as in the Save text box
                if (NodeCurrentReceipt["ReceiptNumber"].InnerText == txtSave.Text)
                {
                    // If you find it, reserve it
                    NodeCustomerOrder = NodeCurrentReceipt;
                    break;
                }
            }
            // Locate the last receipt number
            ReceiptNumber = int.Parse(txtSave.Text);
    
            // Create an element named Receipt
            XmlElement ElementReceipt = DOMReceipts.CreateElement("Receipt");
            string strReceipt = "<ReceiptNumber>" + ReceiptNumber.ToString() +
                                "</ReceiptNumber>" + strParts +
                                "<PartsTotal>" + txtPartsTotal.Text +
                                "</PartsTotal><TaxRate>" + txtTaxRate.Text +
                                "</TaxRate><TaxAmount>" + txtTaxAmount.Text +
                                "</TaxAmount><OrderTotal>" + txtOrderTotal.Text +
                                "</OrderTotal>";
    
            // Create the XML code of the new element
            ElementReceipt.InnerXml = strReceipt;
    
            // If this is a new customer order
            if (NodeCustomerOrder == null)
            {
                // Add the new receipt to the file
                DOMReceipts.DocumentElement.AppendChild(ElementReceipt);
            } // If the customer order existed already, we will only update it
            else // if (NodeCustomerOrder != null)
            {
                // Replace the existing customer order with the current one
                DOMReceipts.DocumentElement.ReplaceChild(ElementReceipt, _
    				NodeCustomerOrder);
            }
    
            // Save the XML file
            DOMReceipts.Save(Filename);
    
            // Reset the customer order
            btnNewCustomerOrder_Click(sender, e);
        }
    }
  26. Return to the Central form and double-click the Open button
  27. Implement its event as follows:
    private void btnOpen_Click(object sender, EventArgs e)
    {
        XmlDocument DOMReceipts = new XmlDocument();
        string Filename = @"C:\College Park Auto Parts\receipts.xml";
    
        // Check that the file exists. If so, open it
        if (File.Exists(Filename))
        {
            // This variable will allow us to know if we have the receipt number
            bool found = false;
            // Empty the list of selected parts
            lvwSelectedParts.Items.Clear();
    
            // After opening the XML file, store it in the DOM
            DOMReceipts.Load(Filename);
            // Get a reference to the root element
            XmlElement RootReceipts = DOMReceipts.DocumentElement;
    
            // Get a list of the receipts in the file
            XmlNodeList ListOfReceipts = RootReceipts.GetElementsByTagName("Receipt");
    
            // Check each receipt
            foreach (XmlNode nodReceipt in ListOfReceipts)
            {
                // Look for an receipt that has the same number
                // as on the Open text box
                if (nodReceipt["ReceiptNumber"].InnerText == txtOpen.Text)
                {
                    // If you find it, make a note
                    found = true;
                    txtOpen.Text = nodReceipt["ReceiptNumber"].InnerText;
                    txtSave.Text = nodReceipt["ReceiptNumber"].InnerText;
    
                    // Retrieve the values of the receipt
                    // and display them on the form
                    try
                    {
                        foreach (XmlNode nodeReceipt in nodReceipt.ChildNodes)
                        {
                            XmlNode node = nodeReceipt.NextSibling.ChildNodes[0];
    
                            ListViewItem lviReceipt = new ListViewItem(node.InnerText);
                            lviReceipt.SubItems.Add(node.NextSibling.InnerText);
                            lviReceipt.SubItems.Add(node.NextSibling.NextSibling.InnerText);
             lviReceipt.SubItems.Add(node.NextSibling.NextSibling.NextSibling.InnerText);
    lviReceipt.SubItems.Add(node.NextSibling.NextSibling.NextSibling.NextSibling.InnerText);
    
                            lvwSelectedParts.Items.Add(lviReceipt);
                        }
    
                        txtPartsTotal.Text = nodReceipt["PartsTotal"].InnerText;
                        txtTaxRate.Text = nodReceipt["TaxRate"].InnerText;
                        txtTaxAmount.Text = nodReceipt["TaxAmount"].InnerText;
                        txtOrderTotal.Text = nodReceipt["OrderTotal"].InnerText;
                    }
                    catch (NullReferenceException)
                    {
                    }
                }
            }
    
            // If the receipt was not found, let the user know
            if (found == false)
            {
                MessageBox.Show("There is no customer order with that receipt number");
                txtSave.Text = txtOpen.Text;
            }
        }// IF the XML file was not found, let the user know
        else
            MessageBox.Show("The file " + Filename + " was not found");
    }
  28. Locate the Load event and change it as follows:
    private void Central_Load(object sender, EventArgs e)
    {
        ShowAutoParts();
        btnNewCustomerOrder_Click(sender, e);
    }
  29. Return to the Central form and double-click the Close button
  30. Implement the event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  31. Execute the application
  32. Click the New Auto Part button and use the Part Editor to create a few parts 
  33. Close the Part Editor
  34. Create a few customer part orders and save them:
     
    College Park Auto Parts: Customer Order
     
    College Park Auto Parts: Part Selection
  35. Close the forms and return to your programming environment
  36. Execute the application again and open a previously saved order
  37. Close the forms and return to your programming environment
 

Home Copyright © 2010-2011 C#Key Home