Upload
wopatery
View
219
Download
0
Embed Size (px)
Citation preview
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
1/34
This application explores the built-in collection classes of the .NET Framework.
The application is used by a company that sells auto-parts. To start, the company mustcreate the items being sold in the store. Each car part is known for the make (or
manufacturer of the car), the model of the car, the category of the part (this makes it a
little easier to locate, categorize, or identify a part), the part name (a short description),and its unit price.
Once the parts have been created, when a customer comes to the store, a clerk can locatethe desires part in the database.
Practical Learning Practical Learning: Creating the Application
1. Start Microsoft Visual C# and create a new Windows Application namedCollegeParkAutoParts3
2. To create a dialog box, on the main menu, click Project -> Add Windows Form...3. Set the name to MakeEditor and click Add
4. Design the form as follows:
Make EditorControl Text Name Other Properties
Label &Make:TextBox txtMake Modifiers: Public
Button OK btnOK DialogResult: OKButton Cancel btnCancel DialogResult: Cancel
Form Property ValueFormBorderStyle FixedDialog
Text Make EditorStartPosition CenterScreen
AcceptButton btnOKCancelButton btnCancel
MaximizeBox False
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
2/34
MinimizeBox False
ShowInTaskbar False
5. To create a dialog box, on the main menu, click Project -> Add Windows Form...6. Set the name to ModelEditor and click Add
7. Design the form as follows:
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
3/34
College Park Auto Parts: Model Editor
Control Text Name Other PropertiesLabel &Model:
TextBox txtModel Modifiers: Public
Button OK btnOK DialogResult: OKButton Cancel btnCancel DialogResult: CancelForm Property Value
FormBorderStyle FixedDialogText Model Editor
StartPosition CenterScreenAcceptButton btnOK
CancelButton btnCancelMaximizeBox False
MinimizeBox FalseShowInTaskbar False
8. To create a dialog box, in the Solution Explorer, right-click CollegeParkAutoParts2 -> Add -> Windows Form...
9. Set the name to CategoryEditor and click Add10. Design the form as follows:
College Park Auto Parts: Category Editor
Control Text Name Other PropertiesLabel &Category:
TextBox txtCategory Modifiers: PublicButton OK btnOK DialogResult: OK
Button Cancel btnCancel DialogResult: CancelForm Property Value
FormBorderStyle FixedDialogText Category Editor
StartPosition CenterScreenAcceptButton btnOK
CancelButton btnCancelMaximizeBox False
MinimizeBox FalseShowInTaskbar False
11. On the main menu, click Project -> Add Windows Form...12. Set the Name to PartEditor and click Add
13. Design the form as follows:
College Park Auto-Part - Part Editor
Control Text Name Other PropertiesLabel &Year:
TextBox txtItemNumberLabel &Make:
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
4/34
ComboBox cbxMakesButton New C&ategory... btnNewMake
Label M&odel:ComboBox cbxModels
Button New Mo &del... btnNewModel
Label &Category:ComboBox cbxCategoriesButton New Ca&tegory btnNewCategory
Label &Unit Price:TextBox 0.00 txtUnitPrice TextAlign: Right
Label Part #:TextBox txtPartNumber
Label &Part Name:TextBox txtPartName
Button Submit btnSubmitButton Close btnClose DialogResult: Cancel
Form Property ValueFormBorderStyle FixedDialog
Text College Park Auto -Parts: Part EditorStartPosition CenterScreen
MaximizeBox FalseMinimizeBox False
ShowInTaskbar False14. Double-click the New Make button and implement it as follows:
private void btnNewMake_Click(object sender, EventArgs e){
MakeEditor editor = new MakeEditor();
if (editor.ShowDialog() == DialogResult.OK){
if (editor.txtMake.Text.Length > 0){
string strMake = editor.txtMake.Text;
// Make sure the category is not yet in the listif (cbxMakes.Items.Contains(strMake))
MessageBox.Show(strMake + " is already in the list");else
{// Since this is a new category, add it to the combox box
cbxMakes.Items.Add(strMake);}
cbxMakes.Text = strMake;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
5/34
}}
}
15. Return to the Part Editor dialog box and double-click the New Model button
16. Implement the event as follows:
private void btnNewModel_Click(object sender, EventArgs e){
ModelEditor editor = new ModelEditor();
if (editor.ShowDialog() == DialogResult.OK){
if (editor.txtModel.Text.Length > 0){
string strModel = editor.txtModel.Text;
// Make sure the category is not yet in the listif (cbxModels.Items.Contains(strModel))
MessageBox.Show(strModel + " is already in the list");else
{// Since this is a new category, add it to the combox box
cbxModels.Items.Add(strModel);}
cbxModels.Text = strModel;
}}
}
17. Return to the Part Editor dialog box and double-click the New Category button18. Implement the event as follows:
private void btnNewCategory_Click(object sender, EventArgs e){
CategoryEditor editor = new CategoryEditor();
if (editor.ShowDialog() == DialogResult.OK){
if (editor.txtCategory.Text.Length > 0){
string strCategory = editor.txtCategory.Text;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
6/34
// Make sure the category is not yet in the listif (cbxCategories.Items.Contains(strCategory))
MessageBox.Show(strCategory + " is already in the list");else
{
// Since this is a new category, add it to the combox boxcbxCategories.Items.Add(strCategory);}
cbxCategories.Text = strCategory;
}}
}
19. Save the file and close the form20. To create an icon, on the main menu, click Project -> Add New Item...
21. In the Templates list, click Icon File22. Set the Name to cpap1 and click Add
23. Right-click the white area and click Delete Image Type24. Design the 16x16, 16 colors version of the icon as follows:
25. On the main menu, click File -> Save cpap1.ico As
26. Select the bin\Debug folder of the current folder and click Save27. On the main menu, click File -> Close
28. In the Solution Explorer, expand bin and expand Debug29. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
30. In the Templates list, make sure Icon File is selected.Set the Name to cpap2 and click Add
31. Right-click the white area and click Delete Image Type32. Design the 16x16, 16 colors version of the icon as follows:
33. Save the file and close the icon window
34. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...35. In the Templates list, make sure Icon File is selected.
Set the Name to year1 and click Add36. Right-click the white area and click Delete Image Type
37. Design the 16x16, 16 colors version of the icon as follows:
38. Save the file and close the icon window39. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
40. In the Templates list, make sure Icon File is selected.Set the Name to year2 and click Add
41. Right-click the white area and click Delete Image Type42. Design the 16x16, 16 colors version of the icon as follows:
43. Save the file and close the icon window
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
7/34
44. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...45. In the Templates list, make sure Icon File is selected.
Set the Name to make1 and click Add46. Right-click the white area and click Delete Image Type
47. Design the 16x16, 16 colors version of the icon as follows:
Icon Design: Diamond48. Save the file and close the icon window
49. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...50. In the Templates list, make sure Icon File is selected.
Set the Name to make2 and click Add51. Right-click the white area and click Delete Image Type
52. Design the 16x16, 16 colors version of the icon as follows:
Icon Design: Diamond53. Save the file and close the icon window
54. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...55. In the Templates list, make sure Icon File is selected.
Set the Name to model1 and click Add56. Right-click the white area and click Delete Image Type
57. Design the 16x16, 16 colors version of the icon as follows:
58. Save the file and close the icon window59. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
60. In the Templates list, make sure Icon File is selected.Set the Name to model2 and click Add
61. Right-click the white area and click Delete Image Type62. Design the 16x16, 16 colors version of the icon as follows:
63. Save the file and close the icon window
64. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...65. In the Templates list, make sure Icon File is selected.
Set the Name to category1 and click Add66. Right-click the white area and click Delete Image Type
67. Design the 16x16, 16 colors version of the icon as follows:
68. Save the file and close the icon window69. In the Solution Explorer, right- click the Debug folder -> Add -> New Item...
70. In the Templates list, make sure Icon File is selected.Set the Name to category2 and click Add
71. Right-click the white area and click Delete Image Type72. Design the 16x16, 16 colors version of the icon as follows:
Icon Design: Minus
73. Save the file and close the icon window74. In the Solution Explorer, right-click Form1.cs and click Rename
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
8/34
75. Type Central.cs and press Enter twice to display the Central form76. From the Components section of the Toolbox, click ImageList and click the form
77. In the Properties window, click (Name) and type imgAutoParts78. Click the ellipsis button of the Images field
79. In the Image Collection Editor, click Add
80. Locate the folder that contains the icons you created and display it in the Look Incombo box81. Select cpap1.ico and click Open
82. 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 Editor83. Click OK
84. Design the form as follows:
College Park Auto Parts - Form DesignControl Text Name Other Properties
Label Label College Park Auto-Parts Font: Times New Roman,20.25pt, style=Bold
ForeColor: BluePanel Height: 2
GroupBox GroupBox Part IdentificationTreeView TreeView tvwAutoParts ImageList: imgAutoParts
GroupBox GroupBox Available PartsListView ListView lvwAutoParts FullRowSelect: True
GridLines: TrueView: Details
Columns (Name) Text TextAlign WidthcolPartNumber Part #
colPartName Part Name 300colUnitPrice Unit Price Right 80
GroupBox GroupBox Customer Order - Selected PartsLabel Label Part #
Label Label Part NameLabel Label Unit Price
Label Label QtyLabel Label Sub Total
TextBox TextBox txtPartNumberTextBox TextBox txtPartName
TextBox TextBox 0.00 txtUnitPrice TextAlign: RightTextBox TextBox 0 txtQuantity TextAlign: Right
TextBox TextBox 0.00 txtSubTotal TextAlign: RightButton Button Add/Select btnAdd
ListView ListView lvwSelectedParts FullRowSelect: TrueGridLines: True
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
9/34
View: DetailsColumns (Name) Text TextAlign Width
colPartNumberSelected Part # 45colPartNameSelected Part Name 274
colUnitPriceSelected Unit Price Right 58
colQuantitySelected Qty Right 28colSubTotalSelected Sub-Total Right 58GroupBox GroupBox Order Summary
Button Button New Au&to Part... btnNewAutoPartLabel Label Receipt #:
TextBox TextBox txtSaveButton 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: RightButton Button &New Customer Order btnNewCustomerOrder
Label Label Receipt #:TextBox TextBox txtOpen
Button Button Save btnOpenLabel Label Tax Amount:
TextBox TextBox 0.00 txtTaxAmount TextAlign: RightLabel Label Order Total:
TextBox TextBox 0.00 txtOrderTotal TextAlign: RightButton Button Close btnClose
85. Click the Available Parts list view86. In the Properties window, click the Events button and, in the Events section, double-
click DoubleClick87. 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;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
10/34
txtQuantity.Focus();
}
88. Return to the Central form
89. Click the Unit Price text box and, in the Events section of the Properties window,double-click Leave90. Implement the event as follows:
private void txtUnitPrice_Leave(object sender, EventArgs e){
double UnitPrice = 0.00D;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
11/34
int Quantity = 0;
double SubTotal = 0.00D;
try
{
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
12/34
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;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
13/34
txtTotalOrder.Text = PartsTotal.ToString("F");txtTaxAmount.Text = TaxAmount.ToString("F");
txtOrderTotal.Text = OrderTotal.ToString("F");}
91. Return to the Central form and click the Qty text box92. In the Events section of the Properties, click Leave, then click the arrow of itscombo box and select txtUnitPrice_Leave
93. Return to the Central form94. Click the Selected Part list view (the list view in the bottom-right section of the
form)95. In the Events section of the Properties window, double-click DoubleClick
96. 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();}
97. In the Solution Explorer, right-click CollegeParkAutoParts3 -> Add -> Class...
98. Set the name to PartDescription and press Enter99. To create a class that can hold a structured item of a list, change the class as follows:
using System;
namespace CollegeParkAutoParts3{
[Serializable]public class PartDescription
{// These members will be used to define a car part
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
14/34
private long ID;private int yr;
private string mk;private string mdl;
private string cat;
private string name;
Wawan
wedding
pitutprivate double price;
public PartDescription()
{this.ID = 0;
this.yr = 1960;this.mk = "";
this.mdl = "";this.name = "Unknown";
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
15/34
this.price = 0.00;}
public PartDescription(long code, int year, string make,
string model, string type,
string desc, double UPrice){this.ID = code;
this.yr = year;this.mk = make;
this.mdl = model;this.cat = type;
this.name = desc;this.price = UPrice;
}
public long PartNumber{
get { return ID; }set { ID = value; }
}
public int Year{
get { return yr; }set { yr = value; }
}
public string Make{
get { return mk; }set { mk = value; }
}
public string Model{
get { return mdl; }set { mdl = value; }
}
public string Category{
get { return cat; }set { cat = value; }
}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
16/34
public string PartName{
get { return name; }set { name = value; }
}
public double UnitPrice{
get { return (price < 0) ? 0.00 : price; }set { price = value; }
}
public override string ToString(){
return this.PartNumber + " " +this.Year.ToString() + " " +
this.Make + " " +this.Model + " " +
this.Category + " " +this.PartName + " " +
this.UnitPrice;}
}}
100. In the Solution Explorer, right-click CollegeParkAutoParts3 -> Add -> Class...
101. Set the name to PartsOrdered and press Enter102. To create another class intended for a list, change the document as follows:
using System;
namespace CollegeParkAutoParts3{
[Serializable]public class PartsOrdered
{public long PartNumber;
public string PartName;public double UnitPrice;
public int Quantity;public double SubTotal;
}}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
17/34
Wawan
wedding
pitut103. Save all104. Display the Part Editor form and double-click the Submit button105. 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;using System.Runtime.Serialization.Formatters.Binary;
namespace CollegeParkAutoParts3
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
18/34
{public partial class PartEditor : Form
{List lstAutoParts;
. . . No Change
private void btnSubmit_Click(object sender, EventArgs e)
{FileStream stmAutoParts = null;
BinaryFormatter bfmAutoParts = new BinaryFormatter();
// If this directory doesn't exist, create itDirectory.CreateDirectory(@"C:\College Park Auto Parts");
// This is the file that holds the list of itemsstring FileName = @"C:\College Park Auto Parts\Parts.prs";
// Create a random number that will be used to identify the item
Random rnd = new Random();txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
// Make sure the user had selected a make
if (cbxYears.Text.Length == 0){
MessageBox.Show("You must specify the year");cbxYears.Focus();
return;}
// Make sure the user had selected a make
if (cbxMakes.Text.Length == 0){
MessageBox.Show("You must specify the car name");cbxMakes.Focus();
return;}
// Make sure the user had selected a model
if (cbxModels.Text.Length == 0){
MessageBox.Show("You must specify the model of the car");cbxModels.Focus();
return;}
// Make sure the user had selected the part category
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
19/34
if (cbxCategories.Text.Length == 0){
MessageBox.Show("You must specify the part's category");cbxCategories.Focus();
return;
}
// Make sure the user had entered a name/description
if (txtPartName.Text.Length == 0){
MessageBox.Show("You must enter the name (or a " +"short description) for the part");
txtPartName.Focus();return;
}
// Make sure the user had typed a price for the itemif (txtUnitPrice.Text.Length == 0)
{MessageBox.Show("You must enter the price of the item");
txtUnitPrice.Focus();return;
}
// Before saving the new part, find out if there was// already a file that holds the list of parts
// If that file exists, open it and store its parts// in our lstParts variable
if (File.Exists(FileName)){
stmAutoParts = new FileStream(FileName,FileMode.Open,
FileAccess.Read,FileShare.Read);
try
{// Retrieve the list of items from file
lstAutoParts =(List)bfmAutoParts.Deserialize(stmAutoParts);
}finally
{stmAutoParts.Close();
}}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
20/34
// Create the part
PartDescription part = new PartDescription();part.PartNumber = long.Parse(txtPartNumber.Text);
part.Year = int.Parse(cbxYears.Text);
part.Make = cbxMakes.Text;part.Model = cbxModels.Text;part.Category = cbxCategories.Text;
part.PartName = txtPartName.Text;part.UnitPrice = double.Parse(txtUnitPrice.Text);
// Call the Add method of our collection class to add the part
lstAutoParts.Add(part);
// Save the liststmAutoParts = new FileStream(FileName,
FileMode.Create,FileAccess.Write,
FileShare.Write);
try{
bfmAutoParts.Serialize(stmAutoParts, lstAutoParts);
// After saving the item, reset the formcbxYears.Text = "";
cbxMakes.Text = "";cbxModels.Text = "";
cbxCategories.Text = "";txtPartName.Text = "";
txtUnitPrice.Text = "0.00";txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
}finally
{stmAutoParts.Close();
}}
}}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
21/34
106. Display the Centralform
107. Right-click the form and click View Code108. Add the following namespaces in the top section of the file:
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;
using System.Runtime.Serialization.Formatters.Binary;
109. Return to the Central form and double-click the Save button110. Implement its event as follows:
private void btnSave_Click(object sender, EventArgs e){
BinaryFormatter bfmCustomerOrder = new BinaryFormatter();
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
22/34
// We will store our files in the following folder
string strDirectory = @"C:\College Park Auto Parts\Receipts";DirectoryInfo dirInfo = new DirectoryInfo(strDirectory);
string strFilename = strDirectory + "\\" + txtSave.Text + ".cap";
List lstOrderedParts = null;
if (lvwSelectedParts.Items.Count == 0)
return;else
{lstOrderedParts = new List();
for (int i = 0; i < lvwSelectedParts.Items.Count; i++)
{ PartsOrdered part = new PartsOrdered();
part.PartNumber = long.Parse(lvwSelectedParts.Items[i].Text);
part.PartName = lvwSelectedParts.Items[i].SubItems[1].Text;part.UnitPrice = double.Parse(lvwSelectedParts.Items[i].SubItems[2].Text);
part.Quantity = int.Parse(lvwSelectedParts.Items[i].SubItems[3].Text);part.SubTotal = double.Parse(lvwSelectedParts.Items[i].SubItems[4].Text);
lstOrderedParts.Add(part);}
FileStream stmCustomerOrder = new FileStream(strFilename, FileMode.Create);
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
23/34
try
{
bfmCustomerOrder.Serialize(stmCustomerOrder, lstOrderedParts);
}finally
{stmCustomerOrder.Close();
}}
}
111. Save all112. Display the Part Editor form and double-click the Makes combo box
113. Implement its SelectedIndexChanged event as follows:
private void cbxMakes_SelectedIndexChanged(object sender, EventArgs e)
{cbxModels.Text = "";
cbxModels.Items.Clear();
foreach (PartDescription part in lstAutoParts)
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
24/34
if (part.Make == cbxMakes.Text)if (!cbxModels.Items.Contains(part.Model))
cbxModels.Items.Add(part.Model);}
114. Display the Central form and double-click the Add/Select button115. 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;}
foreach (PartDescription part in lstAutoParts)
{if (part.PartNumber == long.Parse(txtPartNumber.Text))
{ListViewItem lviSelectedPart =
new ListViewItem(part.PartNumber.ToString());
lviSelectedPart.SubItems.Add(part.PartName);lviSelectedPart.SubItems.Add(part.UnitPrice.ToString());
lviSelectedPart.SubItems.Add(txtQuantity.Text);lviSelectedPart.SubItems.Add(txtSubTotal.Text);
lvwSelectedParts.Items.Add(lviSelectedPart);}
}
CalculateOrder();}
116. Return to the Central form and double-click the Open button
117. Implement its event as follows:
private void btnOpen_Click(object sender, EventArgs e)
{List lstReceipts = null;
BinaryFormatter bfmReceipts = new BinaryFormatter();FileStream stmReceipts = null;
string strDirectory = @"C:\College Park Auto Parts\Receipts";
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
25/34
string strFilename = "";
DirectoryInfo dirReceipts = new DirectoryInfo(strDirectory);FileInfo[] fleReceipts = dirReceipts.GetFiles();
if (txtOpen.Text.Length == 0){MessageBox.Show("You must enter a receipt number\n" +
"There is no receipt number to " +"open a customer's order");
txtOpen.Focus();return;
}
if (fleReceipts.Length == 0){
MessageBox.Show("There is no customer order to open");txtOpen.Focus();
return;}
else{
lvwAutoParts.Items.Clear();lvwSelectedParts.Items.Clear();
strFilename = strDirectory + "\\" + txtOpen.Text + ".cap";
if (File.Exists(strFilename))
{try
{stmReceipts = new FileStream(strFilename, FileMode.Open);
lstReceipts =(List)bfmReceipts.Deserialize(stmReceipts);
foreach (PartsOrdered part in lstReceipts)
{ListViewItem lviReceiptPart =
new ListViewItem(part.PartNumber.ToString());
lviReceiptPart.SubItems.Add(part.PartName);lviReceiptPart.SubItems.Add(part.UnitPrice.ToString());
lviReceiptPart.SubItems.Add(part.Quantity.ToString());lviReceiptPart.SubItems.Add(part.SubTotal.ToString());
lvwSelectedParts.Items.Add(lviReceiptPart);}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
26/34
}finally
{stmReceipts.Close();
}
CalculateOrder();txtSave.Text = txtOpen.Text;
}else
MessageBox.Show("There is no customer order with that receipt number");}
}
118. Save the file119. Display the Part Editor form and double-click an unoccupied area of its body
120. Implement the Load event as follows:
private void PartEditor_Load(object sender, EventArgs e)
{// Since all values seem ready, prepare to process the item
lstAutoParts = new List();BinaryFormatter bfmAutoParts = new BinaryFormatter();
for (int i = DateTime.Today.Year + 1; i >= 1960; i--)
cbxYears.Items.Add(i.ToString());
// Create a random number that will be used to identify the itemRandom rnd = new Random();
txtPartNumber.Text = rnd.Next(100000, 999999).ToString();
// This is the file that holds the list of partsstring FileName = @"C:\College Park Auto Parts\Parts.prs";
if (File.Exists(FileName))
{FileStream stmAutoParts = new FileStream(FileName,
FileMode.Open,FileAccess.Read,
FileShare.Read);
try{
// Retrieve the list of items from filelstAutoParts =
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
27/34
(List)bfmAutoParts.Deserialize(stmAutoParts);
// Display the car manufacturers in the Make combo box
for (int i = 0; i < lstAutoParts.Count; i++)
{ PartDescription part = (PartDescription)lstAutoParts[i];
if (!cbxMakes.Items.Contains(part.Make))cbxMakes.Items.Add(part.Make);
}
// Display the pats categories in the Category combo boxfor (int i = 0; i < lstAutoParts.Count; i++)
{PartDescription part = (PartDescription)lstAutoParts[i];
if (!cbxCategories.Items.Contains(part.Category))
cbxCategories.Items.Add(part.Category);}
}finally
{stmAutoParts.Close();
}}
}
121. Display the Central form and click the Part # text box122. In the Events section of the Properties window, double-click Leave and implement
the event as follows:
private void txtPartNumber_Leave(object sender, EventArgs e)
{// We will allow the user to enter a part number
// In the beginning, we assume that the user// had entered an invalid number
bool found = false;// This will represent the part found, if any
PartDescription PartFound = null;
// After the user had entered a part number,// check the whole list of parts
foreach (PartDescription part in lstAutoParts){
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
28/34
// If you find a part that holds the number the user had enteredif( part.PartNumber == long.Parse(txtPartNumber.Text) )
{// Mark that part
PartFound = part;
// And update the flag that specifies// that the part has been foundfound = true;
}// If the part number was not found, check the next
} // If no part has that number, the found flag keeps marked as false
// If a part with that number was found...if (found == true)
{// Show the corresponding part name and unit price
txtPartName.Text = PartFound.PartName;txtUnitPrice.Text = PartFound.UnitPrice.ToString("F");
txtQuantity.Text = "1";txtSubTotal.Text = PartFound.UnitPrice.ToString("F");
// Give focus to the quantity in case the user was to increase ittxtQuantity.Focus();
}else
{// Since no part with that number was found,
// reset the text boxestxtPartName.Text = "";
txtUnitPrice.Text = "0.00";txtQuantity.Text = "0";
txtSubTotal.Text = "0.00";
// Let the user know that the part number that// was entered is not in the list
MessageBox.Show("There is no part with that number");}
}
123. Return to the Central form and double-click the New Auto Part button124. Implement the event as follows:
using System;using System.Collections.Generic;
using System.ComponentModel;using System.Data;
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
29/34
using System.Drawing;using System.Text;
using System.Windows.Forms;using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace CollegeParkAutoParts3{
public partial class Central : Form{
int iFileName;List lstAutoParts;
public Central()
{InitializeComponent();
}
void ShowAutoParts(){
tvwAutoParts.Nodes.Clear();TreeNode nodRoot =
tvwAutoParts.Nodes.Add("College Park Auto-Parts","College Park Auto-Parts", 0, 1);
// Show the years nodesfor (int years = DateTime.Today.Year + 1; years >= 1960; years--)
nodRoot.Nodes.Add(years.ToString(), years.ToString(), 2, 3);
tvwAutoParts.SelectedNode = nodRoot;// Expand the root node
tvwAutoParts.ExpandAll();
lstAutoParts = new List();BinaryFormatter bfmAutoParts = new BinaryFormatter();
// This is the file that holds the list of auto parts
string FileName = @"C:\College Park Auto Parts\Parts.prs";
if (File.Exists(FileName)){
FileStream stmAutoParts = new FileStream(FileName,FileMode.Open,
FileAccess.Read,FileShare.Read);
try{
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
30/34
// Retrieve the list of parts from filelstAutoParts =
(List)bfmAutoParts.Deserialize(stmAutoParts);
// Show the makes nodesforeach (TreeNode nodYear in nodRoot.Nodes){
List lstMakes = new List();
foreach (PartDescription part in lstAutoParts){
if (nodYear.Text == part.Year.ToString()){
if (!lstMakes.Contains(part.Make))lstMakes.Add(part.Make);
}}
foreach (string strMake in lstMakes)
nodYear.Nodes.Add(strMake, strMake, 4, 5);}
// Showing the models nodes
foreach (TreeNode nodYear in nodRoot.Nodes){
foreach (TreeNode nodMake in nodYear.Nodes){
List lstModels = new List();
foreach (PartDescription part in lstAutoParts){
if ((nodYear.Text == part.Year.ToString()) &&
(nodMake.Text == part.Make)){
if (!lstModels.Contains(part.Model))lstModels.Add(part.Model);
}
}
foreach (string strModel in lstModels)nodMake.Nodes.Add(strModel, strModel, 6, 7);
}}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
31/34
// Showing the categories nodes
foreach (TreeNode nodYear in nodRoot.Nodes){
foreach (TreeNode nodMake in nodYear.Nodes)
{ foreach (TreeNode nodModel in nodMake.Nodes){
List lstCategories = new List();
foreach (PartDescription part in lstAutoParts){
if ((nodYear.Text == part.Year.ToString()) &&
(nodMake.Text == part.Make) &&(nodModel.Text == part.Model))
{if (!lstCategories.Contains(part.Category))
lstCategories.Add(part.Category);}
}
foreach (string strCategory in lstCategories)nodModel.Nodes.Add(strCategory,
strCategory, 8, 9);}
}}
}finally
{stmAutoParts.Close();
}}
}
private void btnNewAutoPart_Click(object sender, EventArgs e){
PartEditor editor = new PartEditor();
if (editor.ShowDialog() == DialogResult.Cancel)ShowAutoParts();
}}
}
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
32/34
125. Display the Central form and double- click the New Customer Order button126. Implement the event as follows:
private void btnNewCustomerOrder_Click(object sender, EventArgs e)
{ // We will store our files in the following folderstring strDirectory = @"C:\College Park Auto Parts\Receipts";
DirectoryInfo dirInfo = Directory.CreateDirectory(strDirectory);
// Get the list of files, if any, from our directoryFileInfo[] fleList = dirInfo.GetFiles();
// If there is no file in the directory,
// then we will use 1000 as the first file nameif (fleList.Length == 0)
{ iFileName = 1000;
}else // If there was at least one file in the directory
{// Get a reference to the last file
FileInfo fleLast = fleList[fleList.Length - 1];// Get the name of the last file without its extension
string fwe = Path.GetFileNameWithoutExtension(fleLast.FullName);// Increment the name of the file by 1
iFileName = int.Parse(fwe) + 1;}
txtSave.Text = iFileName.ToString();
lvwAutoParts.Items.Clear();
lvwSelectedParts.Items.Clear();}
127. Display the Central form and double-click an unoccupied area of its body
128. Define a new method and implement the Load event as follows:
private void Central_Load(object sender, EventArgs e)
{ShowAutoParts();
btnNewCustomerOrder_Click(sender, e);}
129. Return to the Central form and click the tree view
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
33/34
130. In the Properties window, click the Events button and, in the Events section,double-click NodeMouseClick
131. Implement the event as follows:
private void tvwAutoParts_NodeMouseClick(object sender,TreeNodeMouseClickEventArgs e){
TreeNode nodClicked = e.Node;
if (nodClicked.Level == 4)lvwAutoParts.Items.Clear();
try
{foreach (PartDescription part in lstAutoParts)
{ if ((part.Category == nodClicked.Text) &&
(part.Model == nodClicked.Parent.Text) &&(part.Make == nodClicked.Parent.Parent.Text) &&
(part.Year.ToString() == nodClicked.Parent.Parent.Parent.Text)){
ListViewItem lviAutoPart =new ListViewItem(part.PartNumber.ToString());
lviAutoPart.SubItems.Add(part.PartName);
lviAutoPart.SubItems.Add(part.UnitPrice.ToString("F"));lvwAutoParts.Items.Add(lviAutoPart);
}}
}catch (NullReferenceException)
{}
}
132. Return to the Central form and double-click the Close button133. Implement the event as follows:
private void btnClose_Click(object sender, EventArgs e){
Close();}
134. Execute the application
8/9/2019 In the Events Section of the Properties Window, Double-click Double Click
34/34
135. Click the New Auto Part button and use the Part Editor to create a few parts (let thecomputer generate the part numbers)
136. Close the Part Editor
137. Create a few customer part orders and save them:
College Park Auto Parts: Customer Order
College Park Auto Parts: Part Selection138. Close the forms and return to your programming environment
139. Execute the application again and open a previously saved order140. Close the forms and return to your programming environment
Download