Calling A Button OnClick from a function

后端 未结 3 1707
误落风尘
误落风尘 2021-01-22 13:39

I have a button with OnClick=Button_Click. I want to call Button_Click from another function but the problem is that I need to give it:

(object sender, EventArgs         


        
3条回答
  •  后悔当初
    2021-01-22 14:21

    You could do this

     Button_Click(null,EventArgs.Empty);
    

    although I agree that it's better to extract function that could be called from anywhere.

    For example if you have

    protected void Button_Click(object sender, EventArgs e)
    {
      //some list of code      
    }
    

    this code should be put in some new method and then called from Button_Click or any other method

    private void ExtractedMethod()
    { 
     //some list of code
    }
    
     protected void Button_Click(object sender, EventArgs e)
     {
      ExtractedMethod();    
     }
    

    I recommend you to read a book Refactoring: Improving the Design of Existing Code by Martin Fowler. It's a must on a shelf. You will come back to that book from time to time, it's timeless.

提交回复
热议问题