简体   繁体   English

WinForm C#列表框,单击按钮,txt框。 项目总和

[英]WinForm C# list box ,click button ,txt box. sum of items

Hi I'm trying to create a program that gives the user a list box full of items and their respective prices. 嗨,我正在尝试创建一个程序,为用户提供一个列表框,其中包含所有项目及其各自的价格。 When the user selects an item and clicks the add to order button it will add the item to a order summary listbox and also add the price of that item to a subtotal textbox. 当用户选择一个项目并单击“添加到订单”按钮时,它将将该项目添加到订单摘要列表框中,还将该项目的价格添加到小计文本框中。 I have it almost fully functional but my problem is that I can't get the subtotal to add up. 我几乎可以正常使用它,但是我的问题是我无法将小计加起来。 What I mean is when I add one item to the summary list box it displays the price in the subtotal textbox but when I add a second item to the summary list box it doesn't add to the previous price in the subtotal text box instead it just replaces the price of the first item with the price of the second item. 我的意思是,当我向汇总列表框中添加一个项目时,它会在小计文本框中显示价格,但是当我向汇总列表框中添加第二个项目时,它不会将其添加到小计文本框中的先前价格。只需用第二个项目的价格替换第一个项目的价格。 How can I get them to add up and display them in the subtotal text box? 如何获得它们的总和并将其显示在小计文本框中?

Here's how my code looks now under a btn click event handler: 这是我的代码现在在btn click事件处理程序下的外观:

double subTotal = 0.00; 双小计= 0.00;

if (lstBoxItemSelection.Text =="Item 1 = 1.00")
    { 
         LstBoxSummary.Items.Add("Item 1 = 1.00")
         subTotal += 1.00;
     }

if (lstBoxItemSelection.Text =="Item 2 = 2.00"  )
     { 
         LstBoxSummary.Items.Add("Item 2 = 2.00")
         subTotal += 2.00;
     }

this.txtBoxSubTotal.Text = subtotal.ToString();

Thanks for any help! 谢谢你的帮助!

I think your subTotal variable is a local variable. 我认为您的subTotal变量是局部变量。 That mean the value will be reset each time you click on the button. 这意味着每次您单击按钮时都会重置该值。 Try to put it out of the method : 尝试将其排除在方法之外:

private double subTotal = 0.0;
private void btn_click(Object sender,EventArgs e)
{
   if (lstBoxItemSelection.Text =="Item 1 = 1.00")
   { 
        LstBoxSummary.Items.Add("Item 1 = 1.00")
        subTotal += 1.00;
   }

   if (lstBoxItemSelection.Text =="Item 2 = 2.00"  )
   { 
        LstBoxSummary.Items.Add("Item 2 = 2.00")
        subTotal += 2.00;
   }

   this.txtBoxSubTotal.Text = subtotal.ToString();
}

Your subTotal does only exist in the event handler for that single event. 您的subTotal仅存在于该单个事件的事件处理程序中。 The next time you have a new subTotal. 下次您有一个新的小计。

Move subTotal out of the eventhandler or parse your field and add it to subtotal 将subTotal移出事件处理程序或分析您的字段并将其添加到小计

this.txtBoxSubTotal.Text = (float.Parse(this.txtBoxSubTotal.Text,
                            CultureInfo.InvariantCulture) 
                            + subTotal).ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM