[英]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. 更新 :如果您正在删除菠萝对象,则无需将其存储为_oldValue。 You can remove it directly inside your else statement.
您可以直接在else语句中删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.