我的表单有两个按钮,文本框,列表框和组合框。我遇到的问题是当我尝试按钮时。我无法弄清楚如何从此列表中获取成本值,因此我可以计算订单的总成本。谢谢你的建议。
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
listBox1.Items.Add("The cost for " + amount + "
dozen large, fresh eggs is: " + (cost).ToString("C"));
comboBox1.Text = "";
textBox1.Text = "0";
textBox1.Focus();
comboBox1.Focus();
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
if (amount == 1)
{
listBox1.Items.Add
("The Cost for a fresh quart milk is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " quarts of fresh milk is: " +
(cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " fresh loafs of bread is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
cost = 1.90;
label1.Text = "The Cost is " + (cost).ToString("C") + " per dozen";
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
cost = 1.47;
label1.Text = "The Cost is " + (cost).ToString("C") + " per quart";
}
else
{
cost = 2.12;
label1.Text = "The Cost is " + (cost).ToString("C") + " per loaf";
}
}
private void total_Click(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -2)
{
e.Handled = true;
}
if (e.KeyChar == '-'
&& (sender as TextBox).Text.IndexOf('-') > -2)
{
e.Handled = true;
}
}
}
}
答案 0 :(得分:1)
为什么不使用总类字段并在每次将项目添加到列表框时为其添加金额?然后,您总是可以获得总成本,而无需尝试将其从列表中解析出来。
public partial class Form1 : Form
{
private double cost;
private double total;
int amount = 0;
public Form1()
{
InitializeComponent();
}
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
total += cost;
...
}