简体   繁体   中英

Double press of a button c#

I am struggling to make a button to be pressed multiple times with different outcomes. I have a few buttons to add some strings to a list. The problem is that I want to press the button to add an item and, if I press it again, to delete the same item.

private void labelPineapple_Click(object sender, EventArgs e)
{
     if (!My_Pizza.Items.Contains(pineapple))
     {
         My_Pizza.Items.Add(pineapple);
         labelPineapple.BackColor = Color.Green;
     }
}

You want some kind of toggle behavior, we have this "toggle" behavior when the next click "denies" the last one. If I had some more details on if you have a specific button for each item or if you're a selection a item in a list and then pressing the button, I'd be more precise.

If you're selecting an item and then clicking "remove", you can do something like this:

private void DeleteItem_Click(object sender, EventArgs e)
{
   listBox1.SelectedItems.Remove(listBox1.SelectedItems);
}

If somehow you're using the same button to remove the last value you added, you can use a local variable to store the old value like in:

private void labelPineapple_Click(object sender, EventArgs e)
{
   if (!My_Pizza.Items.Contains(pineapple))
   {
      My_Pizza.Items.Add(pineapple);
      labelPineapple.BackColor = Color.Green;
      _oldValue = pineapple;
   }
   else
   {
      My_Pizza.Items.Remove(_oldValue);
   }
}

If the same button will always and only add/remove the same item, use a toggle button instead.

Sometimes we developers try to solve simple things with harder approaches, when things get too complex, try to write down what you're trying to achieve and the possible solutions.

Update : if you have the pineapple object at the moment you're removing it, you don't need to store it as _oldValue. You can remove it directly inside your else statement.

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