views:

124

answers:

4

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();
}
+5  A: 

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);
Pranay Rana
if I remove the call TextChanged2(sender, e); the method is not called even a single time.
@user359562: man, if you call a method, it is executed, what is the problem?
serhio
have you register event handler by using this line : this.TextChanged1 += new TextChangedEventHandler1(TextChanged2); because its require to register to call event handling function
Pranay Rana
yes. I have registered the event.
My question is if I register the event as in this case, there is no need to explicitly call TextChanged2 method right ? if so, then what is the problem in above code
there is no need to call the event explicitly here if you registred it already. i already explained about your code in my answer
Pranay Rana
@user359562: tell us what do you try do, cause there are any sense of your code.
serhio
A: 

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

serhio
A: 

Try

this.TextChanged1 -= TextChanged2;
LexRema
This is no different from what he already has. The `new TextChangedEventHandler1(...)` is now syntactic sugar.
ChrisF
A: 

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.

stakx