Home > Software design >  How to programmatically invoke the Click event handler of a TextBox
How to programmatically invoke the Click event handler of a TextBox

Time:04-06

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(); 

CodePudding user response:

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);
  • Related