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);
}
pub开发者_开发知识库lic void TextChanged2(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.ToUpper();
}
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);
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);
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.
Use
this.TextChanged1 -= TextChanged2;
精彩评论