需要帮助在列表框中附加变量

时间:2015-05-11 09:28:22

标签: c# listbox append

按下Add按钮时,价格取自第一个列表框中“拆分”行的后半部分。然后将其乘以在textbox中输入的值,或者只是按原样输入到第二个listbox中。

然后我在第二个列表框中添加了一行以及总价格。添加新项目时,代码会删除之前的总价格,并将其替换为新的更新总价格。

我希望在第二个列表框的最后一行的“总价”部分中追加(将第二个listbox中列出的所有价格)加在一起。

以下是我到目前为止编写的代码。

    private void button1_Click(object sender, EventArgs e)
    {
        string TheItem = Convert.ToString(listBox1.SelectedItem);
        string[] theSplits = TheItem.Split(' ');
        string FirstSplit = theSplits[0];
        string SecondSplit = theSplits[1];
        Decimal theNewTotal;
        Decimal theValue;



        if (textBox1.Text == "")
        {
            listBox2.Items.Add(TheItem);
            listBox2.Items.Add("Total Price:" + SecondSplit);
        }
        else
        {
            theValue = Convert.ToDecimal(SecondSplit) * Convert.ToDecimal(textBox1.Text);
            listBox2.Items.Add(textBox1.Text + "x " + TheItem);
            theNewTotal = theValue;

            listBox2.Items.Add("Total Price:" + theNewTotal);               
        }
        if (listBox2.Items.Count > 2)
        {
            int theNumber = listBox2.Items.Count;
            listBox2.Items.RemoveAt(theNumber-3);
        }

    }

1 个答案:

答案 0 :(得分:0)

首先删除总价最好,因为你花了一些力气试图解决这个问题。如下所示:

private void button1_Click(object sender, EventArgs e) {
   RemoveLastTotal();
   AppendPrices();
   AppendTotal();
}

private void RemoveLastTotal() {
   var lastItemIndex = listBox2.Items.Count-1;
   if (listBox2.Items[lastItemIndex].StartsWith("Total Price:"))
   {
       listBox2.Items.RemoveAt(lastItemIndex);
   }
}

private void AppendPrices() {
    string TheItem = Convert.ToString(listBox1.SelectedItem);
    string[] theSplits = TheItem.Split(' ');
    string itemDesc = theSplits[0];
    string itemPrice = theSplits[1];
    float quantity = (string.IsNullOrEmpty(textBox1.Text))? 0: float.Parse(textBox1.Text)

    if (quantity==0) {
       listBox2.Items.Add(TheItem);
    } else {
      var lineTotal = Convert.ToDecimal(itemPrice) * quantity;
      listBox2.Items.Add(textBox1.Text + " x " + TheItem + " = " + lineTotal);
   }        
}

private void AppendTotal()
{
    var total = 0;
    foreach(var item in listBox2.Items)
    {
      var splits = item.Split(' ');
      total += decimal.parse(splits[splits.length-1]);
    }
    listBox2.Items.Add("Total Price:" + total);               
}

那就是说,如果你真的想这么做"正确",你应该将视图,即列表框与模型(例如DataTable)分开。

相关问题