How do I exit from a function?

前端 未结 7 1287
野的像风
野的像风 2021-02-18 20:18

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:

pr         


        
相关标签:
7条回答
  • 2021-02-18 20:49

    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
        }
    }
    
    0 讨论(0)
  • 2021-02-18 20:52

    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
        }
    }
    
    0 讨论(0)
  • 2021-02-18 20:53

    There are two ways to exit a method early (without quitting the program):

    i) Use the return keyword.
    ii) Throw an exception.

    Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

    If your method returns void then you can write return without a value:

    return;
    
    0 讨论(0)
  • 2021-02-18 20:54
    return; // Prematurely return from the method (same keword works in VB, by the way)
    
    0 讨论(0)
  • 2021-02-18 20:56

    Use the return statement.

    MSDN Reference

    0 讨论(0)
  • 2021-02-18 21:01

    Use the return keyword.

    return; //exit this event
    
    0 讨论(0)
提交回复
热议问题