我有一个简单的应用程序,其中值被添加到列表框中,作为double的价格在项目的右侧作为字符串。我为标签编写了代码,每次将项目添加到列表框时都会增加价格。当我从列表框中删除选定项时,如何更新标签。
public void Form2_Load(object sender, EventArgs e)
{
foreach (Control butt in groupBox2.Controls)
{
if (butt is Button)
{
((Button)butt).Click += Form2_Click;
}
}
}
public void Form2_Click(object sender, EventArgs e)
{
string st1 = ((Button)sender).Text;
if (st1 == "Family_Pizza")
{
price = 22.95;
}
else if (st1 == "Large_Pizza")
{
price = 16.95;
}
else if (st1 == "Medium Pizza")
{
price = 11.95;
}
else if (st1 == "Small Pizza")
{
price = 7.95;
}
else if (st1 == "Garlic Bread")
{
price = 4.95;
}
else if (st1 == "BBQ Ribs")
{
price = 9.95;
}
else if (st1 == "BBQ Wings")
{
price = 9.95;
}
else if (st1 == "Express Combo")
{
price = 5.95;
}
else if (st1 == "1.25 L Drink")
{
price = 4.50;
}
else if (st1 == "375 ml Drink")
{
price = 2.60;
}
else if (st1 == "600 ml Drink")
{
price = 3.50;
}
else if (st1 == "Ben 'n' Jerry Core")
{
price = 13.50;
}
else if (st1 == "Ben 'n' Jerry Pint")
{
price = 11.95;
}
s2 = price.ToString("C");
string item = st1;
string value=s2.PadLeft(s2.Length+8,' ');
listBox1.Items.Add(item+value);
updprice = price + updprice;
label2.Text = updprice.ToString("C");
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
答案 0 :(得分:1)
在您的活动button3_Click
,您需要在删除列表框项目之前设置标签值:
private void button3_Click(object sender, EventArgs e) {
double price = 0;
if (listBox1.SelectedItem.ToString().IndexOf("Family_Pizza") > -1) {
price = 22.95;
}
.
.
.
else if (listBox1.SelectedItem.ToString().IndexOf("Ben 'n' Jerry Pint") > -1) {
price = 11.95;
}
double label_value = Convert.ToDouble(label2.Text.Replace("$", ""));
label_value -= price;
label2.Text = label_value.ToString("C");
listBox1.Items.Remove(listBox1.SelectedItem);
}