We will read the toppings file into lists. Declare the following variable lists in the location shown:
public partial class Form1 : Form
{
List<String> toppings = new List<String> { };
List<Double> costs = new List<Double> { };
List<CheckBox> chkToppings = new List<CheckBox> { };
public Form1()
...
Write the code to read the topping file
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);
// Create a new check box and add it to the form and list
CheckBox chk = new CheckBox();
// Add the new check box to the list:
chkToppings.Add(chk);
// Set the text of the check box. Example: Sausage $2.00
chk.Text =parts[0] + " "+cost.ToString("$0.00");
// Add the new chkbox to the controls on the form:
this.Controls.Add(chk);
// Position each checkbox so that it is under the previous one:
chk.Location = new System.Drawing.Point(20, y);
// Add the event for each check box so that when it is clicked the Control_click event is executed.
chk.Click += new EventHandler(Control_Click);
// Increment y so that the next check box is under this one.
y += 30;
}
}
private void Control_Click(object sender, EventArgs e)
{
// Click Event for all of the controls
CalculateCost();
}
private void CalculateCost()
{
// TO-DO later
}
For now, you can call getToppings from form load to test.