【问题标题】:Need help appending a variable in listbox需要帮助在列表框中附加变量
【发布时间】:2015-07-21 17:46:58
【问题描述】:

当按下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);
        }

    }

【问题讨论】:

  • 如果你展示几个 8textual) 例子可能会更好。因此,举个例子,列表框 1 和列表框 2 中的内容以及单击后您期望的位置(顺便说一句,您在文本中提到了第二个列表框,但代码仅使用 1 个列表框?)
  • 您面临的具体问题是什么?删除时?

标签: c# listbox append


【解决方案1】:

您最好先删除总价,因为您会花费一些精力来解决这个问题。所以像:

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)。

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2010-12-30
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多