Data Set Example Application: College Park Auto-Parts
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
21 min read4,568 words
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
- Start Microsoft Visual Studio and create a new Windows Forms Application named CollegeParkAutoParts2
- To create an icon, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> New Item...
- In the Templates list, click Icon File
- Set the Name to cpap1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- On the main menu, click File -> Save cpap1.ico As
- Select the bin\Debug folder of the current folder and click Save
- On the main menu, click File -> Close
- In the Solution Explorer, expand bin and expand Debug
- In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to cpap2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to year1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to year2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to make1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to make2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to model1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to model2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to category1 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
- In the Templates list, make sure Icon File is selected. Set the Name to category2 and click Add
- Right-click the white area and click Delete Image Type
- Design the 16x16, 16 colors version of the icon as follows:
- Save the file and close the icon window
- In the Solution Explorer, right-click Form1.cs and click Rename
- Type Central.cs and press Enter twice to display the Central form
- From the Components section of the Toolbox, click ImageList and click the form
- In the Properties window, click (Name) and type imgAutoParts
- Click the ellipsis button of the Images field
- In the Image Collection Editor, click Add
- Locate the folder that contains the icons you created and display it in the Look In combo box
- Select cpap1.ico and click Open
- 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
- Click OK
- Design the form as follows: Control Text Name Other Properties Label College Park Auto-Parts Font: Times New Roman, 20.25pt, style=Bold ForeColor: Blue Panel Height: 2 GroupBox Part Identification TreeView tvwAutoParts ImageList: imgAutoParts GroupBox Available Parts 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 Customer Order - Selected Parts Label Part # Label Part Name Label Unit Price Label Qty Label Sub Total TextBox txtPartNumber TextBox txtPartName TextBox 0.00 txtUnitPrice TextAlign: Right TextBox 0 txtQuantity TextAlign: Right TextBox 0.00 txtSubTotal TextAlign: Right Button Add/Select btnAdd 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 Order Summary Button New Au&to Part... btnNewAutoPart Label Receipt #: TextBox txtSave Button Save btnSave Label Tax Rate: TextBox 7.75 txtTaxRate TextAlign: Right Label % Label Parts Total: TextBox 0.00 txtPartsTotal TextAlign: Right Button &New Customer Order btnNewCustomerOrder Label Receipt #: TextBox txtOpen Button Save btnOpen Label Tax Amount: TextBox 0.00 txtTaxAmount TextAlign: Right Label Order Total: TextBox 0.00 txtOrderTotal TextAlign: Right Button Close btnClose
- Click the Available Parts list view
- In the Properties window, click the Events button and, in the Events section, double-click DoubleClick
- 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(); }
- Return to the Central form
- Click the Unit Price text box and, in the Events section of the Properties window, double-click Leave
- 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"); }
- Return to the Central form and click the Qty text box
- In the Events section of the Properties, click Leave, then click the arrow of its combo box and select txtUnitPrice_Leave
- On the Central form, click the Selected Part list view (the list view in the bottom-right section of the form)
- In the Events section of the Properties window, double-click DoubleClick
- 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(); }
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to ItemsCategories and click Add
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Categories (Name): dsCategories
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Category (Name): tblCategory
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: CategoryName (Name): colCategoryName
- Click Close and click Close
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right DataSource: dsCategories DataMember: Category Button Close btnClose Anchor: Bottom, Right
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to CarMakes and click Add
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Makes (Name): dsMakes
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Make (Name): tblMake
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: MakeName (Name): colMakeName
- Click Close and click Close
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right DataSource: dsMakes DataMember: Makes Button Close btnClose Anchor: Bottom, Right
- To create a dialog box, on the main menu, click Project -> Add Windows Form...
- Set the name to CarModels and click Add
- Display the list of makes form
- Right-click dsMakes and click Copy
- Display the list of models form
- Right-click its body and click Paste
- From the Data section of the Toolbox, click DataSet and click the form
- On the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: Models (Name): dsModels
- Click the Tables field and click its ellipsis button
- In the Tables Collection Editor, click Add
- In the Properties list, change the characteristics of the table as follows: TableName: Car (Name): tblCar
- Click Columns and click its ellipsis button
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: Make (Name): colMake
- In the Columns Collection Editor, click Add
- Change the characteristics of the columns as follows: ColumnName: Model (Name): colModel
- Click Close and click Close
- From the Data section of the Toolbox, click DataGridView and click the form
- In the Properties window, change its characteristics as follows: DataSource: dsModels DataMember: Models
- 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
- Click OK
- Design the form as follows: Control Text Name Additional Properties DataGridView dgvStudents Anchor: Top, Bottom, Left, Right Button Close btnClose Anchor: Bottom, Right
- To create a new form, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> Windows Form...
- Set the Name to AutoParts and click Add
- Display the list of models form
- Click dsMakes
- Press and hold Shift
- Click dsModels
- Release Shift
- Press Ctrl + C
- Display the auto parts form
- Right-click its body and click Paste
- Display the list of categories form
- Right-click dsCategories and click Copy
- Display the auto parts form
- Right-click its body and click Paste
- From the Data section of the Toolbox, click DataSet and click the form
- In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: StoreItems (Name): dsStoreItems
- Click Tables and click its ellipsis button
- In the Properties list, change the characteristics of the table as follows: TableName: StoreItem (Name): tblStoreItem
- Click Columns and click its ellipsis button
- 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
- Click Close and click Close
- From the Data section of the Toolbox, click DataGridView and click the form
- In the Properties window, change its characteristics as follows: DataSource: dsStoreItems DataMember: StoreItems
- 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
- Click OK
- Design the form as follows: 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
- 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(); } } }
- Return to the Part Editor dialog box and double-click the New Model button
- Implement the event as follows: private void btnNewModel_Click(object sender, EventArgs e) { CarModels frmModels = new CarModels(); frmModels.ShowDialog(); }
- Return to the Part Editor dialog box and double-click the New Category button
- Implement the event as follows: private void btnNewCategory_Click(object sender, EventArgs e) { ItemsCategories frmCategories = new ItemsCategories(); frmCategories.ShowDialog(); }
- Display the Central form and double-click the New Auto Part button
- 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(); }
- Execute the application to make sure everything is working fine
- Close the form(s) and return to your programming environment
Practical Learning: Saving the Records of a Data Set
- Display the ItemsCategories form and double-click the Close button
- 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(); } } }
- Display the CarMakes form and double-click the Close button
- 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(); } } }
- Display the Models form and double-click the Close button
- 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(); } } }
- Display the Auto Parts form and double-click the Close button
- 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(); }
- Save all
Practical Learning: Opening the Records for a Data Set
- Display the ItemsCategories form and double-click an unoccupied area of its body
- 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); }
- Display the CarMakes form and double-click an unoccupied area of its body
- 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); }
- Display the CarModels form and double-click an unoccupied area of its body
- 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); }
- Display the AutoParts form and double-click an unoccupied area of its body
- 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); }
- Return to the form and, in the Properties window, click the Events button
- 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); }
- Execute the application
- Click the New Auto Part button and click the New Make button
- Create a few makes as follows: Ford Dodge Toyota Honda
- 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
- Click the New Category button and create a few categories as follows: Exhaust Air Intake Fuel Injection Cooling System Engine Electrical
- Close the form(s) and return to your programming environment
Practical Learning: Getting the Values of a Data Set
- In the Solution Explorer, Double-click Central.cs
- From the Data section of the Toolbox, click DataSet and click the form
- In the Add Dataset dialog box, click the Untyped dataset radio button and click OK
- In the Properties window, change the characteristics of the data set as follows: DataSetName: StoreItems (Name): dsStoreItems
- Click Tables and click its ellipsis button
- In the Properties list, change the characteristics of the table as follows: TableName: AutoPart (Name): tblAutoPart
- Click Columns and click its ellipsis button
- 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
- Click Close and click Close
- Right-click the form and click View Code
- 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); } } } } }
- Return to the form and double-click an unoccupied area of its body to generate its Load event
- Implement the event as follows: private void Central_Load(object sender, EventArgs e) { ShowAutoParts(); }
- Return to the Central form and click the Part # text box
- 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"; } } }
- Return to the Central form and double-click the Add/Select button
- 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(); }
- 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
- Return to the Central form and double-click the New Customer Order button
- 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(); }
- Return to the Central form and click the tree view
- In the Properties window, click the Events button and, in the Events section, double-click NodeMouseClick
- 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) { } }
- Return to the Central form and double-click the Save button
- 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); } }
- Return to the Central form and double-click the Open button
- 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"); }
- Locate the Load event and change it as follows: private void Central_Load(object sender, EventArgs e) { ShowAutoParts(); btnNewCustomerOrder_Click(sender, e); }
- Return to the Central form and double-click the Close button
- Implement the event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
- Execute the application
- Click the New Auto Part button and use the Part Editor to create a few parts
- Close the Part Editor
- Create a few customer part orders and save them:
- Close the forms and return to your programming environment
- Execute the application again and open a previously saved order
- Close the forms and return to your programming environment
Home Copyright © 2010-2011 C# Key Home

