eMi
eMi

Reputation: 5618

C# object sender - getting the Method from which it was called

I've got these Methods:

    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }

And,

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }

How can I handle this, to know if it was called from the Button_click? Do I have to use the object sender to get informations? But how?

Hope u guys can help me

Upvotes: 4

Views: 1928

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292455

Just use a flag:

private bool _isInButtonClick;

private void button_Click(object sender, EventArgs e)
{
      try
      {
          _isInButtonClick = true;
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
      }
      finally
      {
          _isInButtonClick = false;
      }
}


 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         if(_isInButtonClick)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }

Upvotes: 4

Binary Worrier
Binary Worrier

Reputation: 51711

private void richTextBox_TextChanged(object sender, EventArgs e)

Here sender is the richTextBox, not the button that changed the text.

You could go into the stack trace to discover if the button click is on the call stack, but that's overkill (like using a nuke to crack a walnut).

Add a flag (bool) to your form, set it to true in the button click, and check it in the TextChanged event, then at the end of the button click, set it to false again.

If you do this I would advise wrapping this signal logic in a class that implements IDispose and use it in using statements.

That said, are you sure you need this functionality?

Upvotes: 2

Related Questions