tags:

views:

172

answers:

6

i know that in vb.net you can just do Exit Sub

but i would like to know how do i exit a click event in a button?

here's my code:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
    {
        //exit this event
    }
}
+5  A: 
return;

Wouldn't hurt to read a beginner tutorial/book to C#.

Matti Virkkunen
+6  A: 
return; // Prematurely return from the method (same keword works in VB, by the way)
Rowland Shaw
+8  A: 

Use the return keyword.

Charles
+10  A: 

Use the return keyword.

From MSDN:

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.

So in your case, the usage would be:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
    {
        return; //exit this event
    }
}
Donut
+1  A: 

I'd suggest trying to avoid using return/exit if you don't have to. Some people will devoutly tell you to NEVER do it, but sometimes it just makes sense. However if you can structure you checks so that you don't have to enter into them, I think it makes it easier for people to follow your code later.

Thyamine
Disagree with you in so many ways.The reason some people think like that is because they write functions that are way too long.
Stormenet
Kevin
I agree. In the example listed though, rather than check for empty and have to use return inside, I'd suggest checking for conditions that don't require the use of a return later.
Thyamine
Returning in the middle of a function is perfectly acceptable. @Thyamine: What exactly do you mean by "checking for conditions that don't require the use of a return late"?
Matti Virkkunen
+1  A: 

Yo can simply google for "exit sub in c#".

Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)

Or another solution is to get not of these conditions:

private void button1_Click(object sender, EventArgs e)
{
    if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
    {
        //do events
    }
}

And better use String.IsNullOrEmpty:

private void button1_Click(object sender, EventArgs e)
{
    if (!(String.IsNullOrEmpty(textBox1.Text)
    || String.IsNullOrEmpty(textBox2.Text)
    || String.IsNullOrEmpty(textBox3.Text)))
    {
        //do events
    }
}
HasanGursoy