简体   繁体   中英

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.

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.

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. Which

This should work it will remove 600 from the total TextBox:

    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 + "";
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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