user359562
user359562

Reputation: 57

C# event and delegate

I want to detach the custom event but could not detach. Below I am using -= to detach the event. I assume after this, the TextChanged2 method should not be invoked as I have unregistered the event. Is my understanding wrong?

public delegate void TextChangedEventHandler1(object sender, TextBoxargs ta);
public event TextChangedEventHandler1 TextChanged1;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    this.TextChanged1 -= new  TextChangedEventHandler1(TextChanged2);
    TextChanged2(sender, e);
}

public void TextChanged2(object sender, EventArgs e)
{
    textBox1.Text = textBox1.Text.ToUpper();
}

Upvotes: 2

Views: 1004

Answers (4)

Sasha Reminnyi
Sasha Reminnyi

Reputation: 3532

Use

this.TextChanged1 -= TextChanged2;

Upvotes: 1

I suggest you give some more reasonable names to your methods, controls, and events. I could imagine half the confusion here stems from confusing names.

For example, in one comment to an answer, you mention that if you don't call the TextChanged2 event handler (for the TextChanged1 event...) explicitly, it will never get called. This would lead to the question when, and where, you raise the TextChanged1 event. If you have indeed subscribed the TextChanged2 handler to the TextChanged1 event with the += operator, then the handler will be invoked as soon as the event is raised.

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176956

What you are doing is right. But using the following line of the code you can detach the event handler.

this.TextChanged1 -= new  TextChangedEventHandler1(TextChanged2);

But on the second line you called the function directly so that it called the textchange2 function:

TextChanged2(sender, e);

Upvotes: 6

serhio
serhio

Reputation: 28586

I want to detach the custom event but could not detach.

You do. You detach very well your event.

TextChanged2 method should not be invoked as I have unregistered the event.

It should not be invoked when this.textChanged1, but you invoke it yourself by calling TextChanged2(sender, e);

Upvotes: 1

Related Questions