Search code examples
c#winformseventstextboxclick

How to programmatically invoke the Click event handler of a TextBox


I know how to programmatically invoke the event handler of a Button:

button1.PerformClick();   

I would like to do the same for the Click event handler of a TextBox. The problem is that TextBox does not have a

textBox1.PerformClick(); 

Solution

  • I suggest method extraction (why should we mix UI - windows messages and Business Logic):

    //TODO: put a better name here 
    private void onMyTextBoxClick() {
      //TODO: relevant code here
    }
    
    private void MyTextBox_Click(object sender, EventArgs e) {
      onMyTextBoxClick();
    }
    

    Then you can just call onMyTextBoxClick:

    ...
    // Same business logic as if MyTextBox is clicked
    onMyTextBoxClick();
    ...
    

    Edit: If you really want EventArgs aruments, just provide them:

    //TODO: put a better name here 
    private void onMyTextBoxClick(TextBox box, EventArgs e) {
      //TODO: relevant code here
    }
    
    // Default EventArgs
    private void onMyTextBoxClick(TextBox box) {
      onMyTextBoxClick(box, EventArgs.Empty);
    }
    
    // Both TextBox and EventArgs are default ones
    private void onMyTextBoxClick() {
      onMyTextBoxClick(MyTextBox, EventArgs.Empty);
    }
    
    private void MyTextBox_Click(object sender, EventArgs e) {
      onMyTextBoxClick(sender as TextBox, e);
    }
    

    Usage:

    // Default EventArgs
    onMyTextBoxClick(myTextBox);
    
    // Custom EventArgs
    EventArgs args = ...
    
    onMyTextBoxClick(myTextBox, args);