简体   繁体   English

c#从列表框中删除项目,然后它将从文本框中扣除值

[英]c# removing item from listbox then it will deduct the value from the textbox

after i delete an item to the listbox it will also deduct the value from the textbox. 在我将一个项目删除到列表框中后,它还将从文本框中扣除该值。 here's my code. 这是我的代码。

private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        int total1 = Convert.ToInt32(txtTotal.Text);


        if (listBox1.Text =="item1 600")
        {

            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            total1 -= 600;
        }
    }

Thanks in advance! 提前致谢!

You should probably think about creating an object that holds the two pieces of information. 您可能应该考虑创建一个包含两个信息的对象。 With the object you could override the .ToString() method to only show Item1 and get the 600 from the non-viewed property. 使用该对象,您可以覆盖.ToString()方法以仅显示Item1并从非查看属性中获取600。

Something like: 就像是:

public class MyItem
{
   public string Text {get; set;}
   public string Amount {get; set;}

   public override string ToString()
   {
       return Text;
   }
} 

Then you can instantiate a new object and set the Name and Amount properties and then add it to your listbox. 然后,您可以实例化一个新对象并设置Name和Amount属性,然后将其添加到列表框中。

When you are about to remove your item, you can get the Amount from the object and subtract it from your total. 当您要删除项目时,可以从对象中获取金额,然后从总计中减去。 This would alleviate you having to create an If statement for every item in your list. 这将减轻您不得不为列表中的每个项目创建If语句的麻烦。 Which 哪一个

This should work it will remove 600 from the total TextBox: 这应该可以正常工作,它将从总的TextBox中删除600:

    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        int total1 = int.Parse(txtTotal.Text);

        if (listBox1.SelectedValue.ToString() == "item1 600")
        {

            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            total1 -= 600;

            txtTotal.Text = total1 + "";
        }
    }

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

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