Trigger event only once

7

I'm doing an interface in Visual Studio 2015, how do I perform an event only once?

For example:

private void textBox5_Click(object sender, EventArgs e)
{  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";        
}

When the user clicks on the text box, the color changes to black, and then selects everything and cleans up.

But I want this to happen only once, that is, if the user clicks again, do nothing.

    
asked by anonymous 08.04.2016 / 19:31

2 answers

10

Unlink the event from the component.

So, whenever the form is "built" the event will be linked to the component, and when it is first triggered, it will be unlinked.

Maybe not the best way to do it, but without further details it's hard to think of a better way.

private void textBox5_Click(object sender, EventArgs e)
{  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";

    textBox5.Click -= textBox5_Click;
}
    
08.04.2016 / 19:37
6

It's quite simple. I can not give too many details because I did not see the whole code, but in essence it is only to be disinclined in the event. If this object can subscribe, you can do the opposite:

private void textBox5_Click(object sender, EventArgs e) {  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";
    textBox5.Click -= textBox5_Click; //provavelmente isto
}
    
08.04.2016 / 19:39