// Programmer: Janet Joy // Add check boxes for pizza toppings dynamically. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Pizza { public partial class Form1 : Form { List toppings = new List { }; List costs = new List { }; List chkToppings = new List { }; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Load the toppings from the file. String fileName = @"c:\mydata\pizzatoppings.txt"; // Include using System.IO; to use File.Exists. if (File.Exists(fileName)) getToppings(fileName); else MessageBox.Show(fileName + " Not Found", "No toppings available", MessageBoxButtons.OK); // To do: Let the user select a file. // Add the click event for every control on the form. foreach (Control ctrl in this.Controls) { ctrl.Click += new EventHandler(Control_Click); } // Show cost at start for default size. CalculateCost(); } private void getToppings(String filename) { // Read one line at a time Example: sausage,2.00 String line; // Parts will have "sausage", "2.00" after spliting line. String[] parts; // "2.00" must be converted to double 2.00 Double cost,total=0.0; // Starting position for first checkbox is beneath cost int y = lblCost.Location.Y + lblCost.Width + 10; System.IO.StreamReader file =new System.IO.StreamReader(filename); // Read the file line by line. while ((line = file.ReadLine()) != null) { // split the line on the comma: "sausage,2.00" becomes parts[0]="sausage"; parts[1]=",2.00"; parts = line.Split(','); // Add name to toppings. toppings.Add(parts[0]); // Get cost and add to list costs Double.TryParse(parts[1], out cost); costs.Add(cost); total += cost; // Create a new check box and add it to the form and list CheckBox chk = new CheckBox(); chkToppings.Add(chk); chk.Text =parts[0] + " "+cost.ToString("$0.00"); this.Controls.Add(chk); chk.Location = new System.Drawing.Point(20, y); chk.Click += new EventHandler(Control_Click); // Increment y so that the next check box is under this one. y += 30; } //this.Text = total.ToString("$0.00"); } private void Control_Click(object sender, EventArgs e) { // This event handles the click event for every control on the form. CalculateCost(); } private void CalculateCost() { Double cost = 0; // Get the base price for the size. if (radSmall.Checked) cost = 9.00; else if (radMedium.Checked) cost = 10.00; else cost = 12.00; // Extra cheese is $1.50. if (chkCheese.Checked) cost += 1.50; // Add the cost for each topping that is checked. for(int i=0;i