Introduction

A database is used to hold records. Most databases use records that depend on other records that in turn may depend on other records. Sometimes the scenarios become complex. One way to create and manage those records is to use a data set. To make the task easy, the .NET Framework includes a whose library for data sets. Up to Microsoft Visual Studio 2019, you can visually create the data set, its tables, the columns of those tables, and their records.

Practical Learning: Introducing Data Sets

  1. Start Microsoft Visual Studio
  2. On the Visual Studio (2019 or 2022) dialog box, click Create a New Project
  3. On the Create a New Project wizard page, in the languages combo box, select C# and, in the list of projects templates, click Windows Forms App(.NET Framework)
  4. Click Next
  5. In the Configure Your New Project wizard page, change the Project Name to CollegeParkAutoParts1
  6. Accept or change the project Location.
    In the Framework combo box, select the highest version (.NET Framework 4.8).
    Click Create

The Vehicles Makes

The business of this application is to sell auto-parts. When a customer wants to purchase an auto part, the first relevant piece of information to provide is the make of the vehicle on which the part will be used.

Practical Learning: Introducing Vehicles Makes

  1. To create a dialog box, on the main menu, click Project -> Add Form (Windows Forms)...
  2. Change the Name to VehiclesMakes
  3. Click Add
  4. On the left side, click Toolbox and expand its Data node. In the Data section of the Toolbox, click DataSet
  5. Click the form
  6. On the Add Dataset dialog box, click the Untyped dataset radio button

    Add Data Set

  7. Click OK
  8. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Makes
    (Name): dsMakes
  9. Click the Tables field and click its ellipsis button
  10. In the Tables Collection Editor, click Add
  11. In the Properties list, change the characteristics of the table as follows:
    TableName: VehicleMake
    (Name): dtVehicleMake
  12. Click Columns and click its ellipsis button
  13. In the Columns Collection Editor, click Add
  14. Change the characteristics of the columns as follows:
    ColumnName: Make
    (Name): colMakeVehicle
  15. In the Columns Collection Editor dialog box, click Close

    Columns Collection Editor

  16. In the Tables Collection Editor dialog box, click Close
  17. Design the form as follows:

    College Park Auto-Parts: Makes

    Control Text Name Additional Properties
    DataGridView DataGridView   dgvMakes Anchor: Top, Bottom, Left, Right
    DataSource: dsMakes
    DataMember: Makes
    Button Button Close btnClose Anchor: Bottom, Right
  18. Double-click an unoccupied area of the form
  19. Return to the Vehicles Makes form and double-click the Close button
  20. Change the document as follows:
    using System.IO;
    
    
    namespace CollegeParkAutoParts1
    {
        public partial class VehiclesMakes : Form
        {
            public Makes()
            {
                InitializeComponent();
            }
    
            private void VehiclesMakes_Load(object sender, EventArgs e)
            {
                string fileName = @"C:\College Park Auto Parts\Makes.xml";
    
                if (File.Exists(fileName))
                    dsMakes.ReadXml(fileName);
            }
    
            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();
            }
        }
    }

Vehicles Models

A vehicle is identified by its model. Our database already includes a table for that. We will just need a form to handle issues related to vehicles models.

Practical Learning: Introducing Vehicles Models

  1. To create a dialog box, on the main menu, click Project -> Add Form (Windows Forms)...
  2. Change the Name to VehiclesModels
  3. Click Add
  4. Display the Vehicles Makes form
  5. Right-click dsMakes and click Copy
  6. Display the Vehicles Models form
  7. Right-click its body and click Paste
  8. From the Data section of the Toolbox, click DataSet and click the form
  9. On the Add Dataset dialog box, click the Untyped dataset radio button

    Add Data Set

  10. Click OK
  11. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Models
    (Name): dsModels
  12. Click the Tables field and click its ellipsis button
  13. In the Tables Collection Editor, click Add
  14. In the Properties list, change the characteristics of the table as follows:
    TableName: VehicleModels
    (Name): dtVehicleModel
  15. Click Columns and click its ellipsis button
  16. In the Columns Collection Editor, click Add
  17. Change the characteristics of the columns as follows:
    ColumnName: Make
    (Name): colVehicleMake
  18. In the Columns Collection Editor, click Add
  19. Change the characteristics of the columns as follows:
    ColumnName: Model
    (Name): colVehicleModel

    Columns Collection Editor

    Columns Collection Editor

  20. In the Columns Collection Editor dialog box, click Close
  21. In the Tables Collection Editor dialog box, click Close
  22. From the Data section of the Toolbox, click DataGridView and click the form
  23. In the Properties window, change its characteristics as follows:
    DataSource: dsModels
    DataMember: CarModel
  24. Right-click the data grid view on the form and click Edit Columns...
  25. Change the columns as follows:
    Selected Columns: HeaderText DataPropertyName ColumnType DataSource DisplayMember
    Make Make Make DataGridViewComboBoxColumn dsMakes VehicleMake.Make
    Model Model Model      

    Edit Columns

  26. Click OK
  27. Design the form as follows:
    College Partk Auto Parts - Vehicles Models
    Control Text Name Additional Properties
    DataGridView DataGridView   dgvModels Anchor: Top, Bottom, Left, Right
    Button Button Close btnClose Anchor: Bottom, Right
  28. Double-click an unoccupied area of the body of the Vehicles Models form
  29. Return to the Models form and double-click its Close button
  30. Change the document as follows:
    using System.IO;
    
    
    namespace CollegeParkAutoParts1
    {
        public partial class VehiclesModels : Form
        {
            public Models()
            {
                InitializeComponent();
            }
    
            private void VehiclesModels_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);
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
                
                Directory.CreateDirectory(strDirectory);
    
                dsModels.WriteXml(strDirectory + "\\Models.xml");
                Close();
            }
        }
    }

Items Categories

To further identify a part of a vehicle, those parts are put in categories, and there are many of those categories. In our application, we will just list the categories based on our opinions.

Practical LearningPractical Learning: Setting Items Categories

  1. To create a dialog box, on the main menu, click Project -> Add Windows Form...
  2. Set the name to Categories and click Add
  3. From the Data section of the Toolbox, click DataSet and click the form
  4. On the Add Dataset dialog box, click the Untyped dataset radio button

    Add Data Set

  5. Click OK
  6. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: Categories
    (Name): dsCategories
  7. Click the Tables field and click its ellipsis button
  8. In the Tables Collection Editor, click Add
  9. In the Properties list, change the characteristics of the table as follows:
    TableName: PartCategory
    (Name): dtPartCategory
  10. Click Columns and click its ellipsis button
  11. In the Columns Collection Editor, click Add
  12. Change the characteristics of the columns as follows:
    ColumnName: Category
    (Name): colItemCategory
  13. In the Columns Collection Editor dialog box, click Close
  14. In the Tables Collection Editor dialog box, click Close
  15. Design the form as follows:

    College Park Auto-Parts: Categories

    Control Text Name Additional Properties
    DataGridView DataGridView   dgvCategoriess Anchor: Top, Bottom, Left, Right
    DataSource: dsCategories
    DataMember: Category
    Button Button Close btnClose Anchor: Bottom, Right
  16. On the Categories form, double-click an unoccupied area of its body
  17. Return to the Categories form and double-click the Close button
  18. Change the document as follows:
    using System.IO;
    
    
    namespace CollegeParkAutoParts1
    {
        public partial class Categories : Form
        {
            public Categories()
            {
                InitializeComponent();
            }
    
            private void Categories_Load(object sender, EventArgs e)
            {
                string fileName = @"C:\College Park Auto Parts\categories.xml";
    
                if (File.Exists(fileName))
                    dsCategories.ReadXml(fileName);
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
                Directory.CreateDirectory(strDirectory);
    
                dsCategories.WriteXml(strDirectory + "\\categories.xml");
                Close();
            }
        }
    }

Store Items Inventory

The primary purpose of the business of our application is to sell auto parts. So it is necessary to create records for those parts. To make this happen, we had already created a table for auto parts. Now we need a graphical object, a form, to manager the records.

Practical LearningPractical Learning: Preparing an Items Inventory

  1. To create a new form, in the Solution Explorer, right-click CollegeParkAutoParts1 -> Add -> Form (Windows Forms)...
  2. Change the Name to AutoParts
  3. Click Add
  4. Display the Models form and click dsMakes
  5. Press and hold Shift
  6. Click dsModels and release Shift
  7. Press Ctrl + C
  8. Display the AutoParts form
  9. Right-click its body and click Paste
  10. Display the Categories form
  11. Right-click dsCategories and click Copy
  12. Display the AutoParts form
  13. Right-click its body and click Paste
  14. From the Data section of the Toolbox, click DataSet
  15. Click the form
  16. In the Add Dataset dialog box, click the Untyped dataset radio button

    Add Data Set

  17. Click OK
  18. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: StoreItems
    (Name): dsStoreItems
  19. In the Properties window, click Tables and click its ellipsis button
  20. In the Properties list, change the characteristics of the table as follows:
    TableName: StoreItem
    (Name): dtStoreItem
  21. Click Columns and click its ellipsis button
  22. 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
  23. In the Columns Collection Editor dialog box, click Close
  24. In the Tables Collection Editor dialog box, click Close
  25. From the Data section of the Toolbox, click DataGridView and click the form
  26. In the Properties window, change its characteristics as follows:
    DataSource: dsStoreItems
    DataMember: StoreItems
  27. Under the Properties window, click Columns and click the button on the right of (Collection)
  28. 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 VehicleMake.Make 85
    Model Model Model DataGridViewComboBoxColumn dsModels VehicleModel.Model 130
    Category Category Category DataGridViewComboBoxColumn dsCategories PartCategory.Category 120
    Part Name Part Name/Description PartName       185
    Unit Price Unit Price UnitPrice       65
  29. Click OK
  30. Design the form as follows:
     
    College Park Auto Parts: Store Items
     
    Control Text Name Other Properties
    DataGridView   dgvStoreItems Anchor: Top, Bottom, Left, Right
    ColumnHeadersHeightSizeMode: EnableResizing
    DataSource: dsStoreItems
    DataMember: StoreItems
    Button Vehicles Makes... btnVehiclesMakes Anchor: Bottom, Right
    Button Vehicles Models... btnVehiclesModels Anchor: Bottom, Right
    Button Parts Categories... btnPartsCategories Anchor: Bottom, Right
    Button Close btnClose Anchor: Bottom, Right
  31. On the Auto Parts form, double-click an unoccupied area of its body
  32. Return to the Auto-Parts form and, in the Properties window, click the Events button Events
  33. In the Events section of the Properties window, double-click Activated
  34. Return to the Auto-Parts form and double-click the Vehicles Makes button
  35. Return to the Auto-Parts form and double-click the Vehicles Models button
  36. Return to the Auto-Parts form and double-click the Parts Categories button
  37. Return to the Auto-Parts form and double-click the Close button
  38. Change the document as follows:
    using System.IO;
    
    namespace CollegeParkAutoParts1
    {
        public partial class AutoParts : Form
        {
            public AutoParts()
            {
                InitializeComponent();
            }
    
            private void AutoParts_Load(object sender, EventArgs e)
            {
                string fileName = @"C:\College Park Auto Parts\StoreItems.xml";
    
                if (File.Exists(fileName))
                    dsStoreItems.ReadXml(fileName);
            }
    
            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);
            }
    
            private void btnNewMake_Click(object sender, EventArgs e)
            {
                Makes frmMakes = new Makes();
                frmMakes.ShowDialog();
            }
    
            private void btnNewModel_Click(object sender, EventArgs e)
            {
                Models frmModels = new Models();
                frmModels.ShowDialog();
            }
    
            private void btnNewCategory_Click(object sender, EventArgs e)
            {
                Categories frmCategories = new Categories();
                frmCategories.ShowDialog();
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                string strDirectory = @"C:\College Park Auto Parts";
    
                Directory.CreateDirectory(strDirectory);
    
                dsStoreItems.WriteXml(strDirectory + "\\StoreItems.xml");
                Close();
            }
        }
    }

Managing the Business

Like most graphical applications, ours will need a central point. This is a form from which a user will select the year of a vehicle, the make, and the model. Then the user will select the category of the part. A section of the form will show the list of parts that respond to the previously mentioned criteria. The user can then select the desired part(s) and process a customer's order.

Practical LearningPractical Learning: Managing the Business

  1. In the Solution Explorer, right-click Form1.cs and click Rename
  2. Type CollegeParkAutoParts (to have CollegeParkAutoParts.cs) and press Enter twice to display the form
  3. From the Components section of the Toolbox, click ImageList and click the form
  4. In the Properties window, click (Name) and type imgAutoParts
  5. Click the ellipsis button of the Images field
  6. In the Image Collection Editor, click Add
  7. Locate the folder that contains the resources for these lessons and display it in the Look In combo box
  8. Select the following icons: Sign1, Sign2, Cliper1, Cliper2, Rulers1, Rulers2, Graph1, Graph2, Tool1, and Tool2
  9. Click Open

    Image Collection Editor

  10. Click OK
  11. From the Data section of the Toolbox, click DataSet and click the form
  12. In the Add Dataset dialog box, click the Untyped dataset radio button

    Add Data Set

  13. Click OK
  14. In the Properties window, change the characteristics of the data set as follows:
    DataSetName: StoreItems
    (Name): dsStoreItems
  15. Click Tables and click its ellipsis button
  16. In the Properties list, change the characteristics of the table as follows:
    TableName: StoreItem
    (Name): dtStoreItem
  17. Click Columns and click its ellipsis button
  18. 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
  19. In the Columns Collection Editor dialog box, click Close
  20. In the Tables Collection Editor dialog box, click Close
  21. 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 Panel     Height: 2
    GroupBox Group Box Part Identification    
    TreeView Tree View   tvwAutoParts ImageList: imgAutoParts
    GroupBox Group Box Available Parts    
    ListView List View   lvwAutoParts FullRowSelect: True
    GridLines: True
    View: Details
    Columns   (Name) Text TextAlign Width
    colAvailablePartNumber Part #    
    colAvailablePartName Part Name   300
    colAvailableUnitPrice Unit Price Right 80
    GroupBox Group Box 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
    colSelectedPartNumber Part #   45
    colSelectedPartName Part Name   274
    colSelectedUnitPrice Unit Price Right 58
    colSelectedQuantity Qty Right 28
    colSelectedSubTotal Sub-Total Right 58
    GroupBox Group Box Order Summary    
    Button Button Au&to Parts... btnAutoParts  
    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  
  22. In the College Park Auto-Parts form, click the Part Identification tree view
  23. In the Properties window, click the Events button
  24. In the Events section of the Properties window, double-click NodeMouseClick
  25. Return to the College Park Auto-Parts form and click the Available Parts list view
  26. In the Events section of the Properties window, double-click DoubleClick
  27. Return to the College Park Auto-Parts form and click the Part # text box
  28. In the Events section of the Properties window, double-click Leave
  29. Return to the College Park Auto-Parts form and click the Unit Price text box
  30. In the Events section of the Properties window, double-click Leave
  31. Return to the College Park Auto-Parts form and click the Qty text box
  32. In the Events section of the Properties, click Leave, then click the arrow of its combo box and select txtUnitPrice_Leave
  33. In the College Park Auto-Parts form, double-click the Add/Select button
  34. Return to the College Park Auto-Parts form and click the Selected Part list view (the list view in the bottom-right section of the form)
  35. In the Events section of the Properties window, double-click DoubleClick
  36. Return to the College Park Auto-Parts form and double-click the Auto Parts button
  37. Return to the College Park Auto-Parts form and double-click the New Customer Order button
  38. Return to the College Park Auto-Parts form and double-click an unoccupied area of its body
  39. Return to the College Park Auto-Parts form and double-click the Save button
  40. Return to the College Park Auto-Parts form and double-click the Open button
  41. Return to the form and double-click the Close button
  42. Change the document as follows:
    using System.IO;
    using System.Xml;
    using System.Data;
    
    using System.Collections.Generic;
    
    namespace CollegeParkAutoRepair1
    {
        public partial class CollegeParkAutoRepair : Form
        {
            public CollegeParkAutoRepair()
            {
                InitializeComponent();
            }
    
            private void tvwAutoParts_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
            {
                TreeNode nodClicked = e.Node;
    
                if (nodClicked.Level == 4)
                    lvwAutoParts.Items.Clear();
    
                try
                {
                    foreach (DataRow row in dtStoreItem.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);
                            break;
                        }
                    }
                }
                catch (NullReferenceException nre)
                {
                    MessageBox.Show("The application produced an error as follows: " +
                                    Environment.NewLine + nre.Message, "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
    
            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();
            }
    
            private void txtPartNumber_Leave(object sender, EventArgs e)
            {
                foreach (DataRow row in dtStoreItem.Rows)
                {
                    if (row["PartNumber"].ToString() == txtPartNumber.Text)
                    {
                        txtPartName.Text = row["PartName"].ToString();
                        txtUnitPrice.Text = row["UnitPrice"].ToString();
                        txtQuantity.Text = "1";
                        txtSubTotal.Text = row["UnitPrice"].ToString();
    
                        txtQuantity.Focus();
                        break;
                    }
                }
            }
    
            private void txtUnitPrice_Leave(object sender, EventArgs e)
            {
                int    quantity  = 0;
                double unitPrice = 0.00D;
    
                try
                {
                    unitPrice = double.Parse(txtUnitPrice.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Unit Price!", "College Park Auto-Parts");
                }
    
                try
                {
                    quantity = int.Parse(txtQuantity.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Quandtity!", "College Park Auto-Parts");
                }
    
                double subTotal = unitPrice * quantity;
                txtSubTotal.Text = subTotal.ToString("F");
            }
    
            internal void CalculateOrder()
            {
                // Calculate the current total order and update the order
                double taxRate    = 0.00d;
                double partsTotal = 0.00D;
    
                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");
                }
    
                double taxAmount = partsTotal * taxRate;
                double orderTotal = partsTotal + taxAmount;
    
                txtPartsTotal.Text = partsTotal.ToString("F");
                txtTaxAmount.Text  = taxAmount.ToString("F");
                txtOrderTotal.Text = orderTotal.ToString("F");
            }
    
            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();
            }
    
            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");
                    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();
            }
    
            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 dtStoreItem.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 dtStoreItem.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 dtStoreItem.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);
                            }
                        }
                    }
                }
            }
    
            private void btnAutoParts_Click(object sender, EventArgs e)
            {
                AutoParts frmParts = new AutoParts();
    
                if (frmParts.ShowDialog() == DialogResult.Cancel)
                    ShowAutoParts();
            }
    
            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";
                lvwAutoParts.Items.Clear();
                lvwSelectedParts.Items.Clear();
            }
    
            private void CollegeParkAutoParts_Load(object sender, EventArgs e)
            {
                // This is the directory in which the records of the database of this application will be saved
                string strDirectory = @"C:\College Park Auto Parts";
    
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(strDirectory);
                
                ShowAutoParts();
                btnNewCustomerOrder_Click(sender, e);
            }
    
            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);
                }
            }
    
            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 nodeSelectedParts in nodReceipt.ChildNodes)
                                {
                                    XmlNode node = nodeSelectedParts.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);
                                }
                            }
                            catch (NullReferenceException /* nre */)
                            {
                                /* MessageBox.Show("The application produced an error as follows: " +
                                    Environment.NewLine + nre.Message, "College Park Auto-Parts",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information); */
                            }
    
                            txtPartsTotal.Text = nodReceipt["PartsTotal"].InnerText;
                            txtTaxRate.Text = nodReceipt["TaxRate"].InnerText;
                            txtTaxAmount.Text = nodReceipt["TaxAmount"].InnerText;
                            txtOrderTotal.Text = nodReceipt["OrderTotal"].InnerText;
    
                            break;
                        }
                    }
    
                    // If the receipt was not found, let the user know
                    if (found == false)
                    {
                        MessageBox.Show("There is no customer order with that receipt number", "College Park Auto-Parts");
                    }
                }// IF the XML file was not found, let the user know
                else
                    MessageBox.Show("The file " + fileName + " was not found", "College Park Auto-Parts");
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }
  43. To execute the application, on the main menu, click Debug -> Start Without Debugging:

  44. Click the Auto Parts button

  45. Click the Vehicles Makes button:

    College Park Auto Parts

  46. From the values in the following list, click the text box below Make, type a value and press the down-point arrow:
     
    Ford
    Dodge
    Toyota
    Honda
  47. Click the Close button to close the Vehicles Makes form
  48. Click the Vehicles Models button
  49. Click the arrow of the combo box below the Makes column header to select a Make. Then type the correspondiong value of the following list in the text box below the Models column. Press the down arrow key to move the next row: 
    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
  50. Click the New Category button and create a few categories as follows:
     
    Exhaust
    Air Intake
    Fuel Injection
    Cooling System
    Engine Electrical
  51. Create a few parts 
  52. Close the Part Editor
  53. Create a few customer part orders and save them:

    College Park Auto Parts: Customer Order

    College Park Auto Parts: Part Selection

  54. Close the forms and return to your programming environment
  55. Close the forms and return to your programming environment

Home Copyright © 2005-2023, FunctionX Wednesday 11 May 2022 Home