In Winforms, we often use event handlers to take various actions at specific events. For example, we may want to show some help message in the status bar when user start typing something in a textbox. We can handle it in the TextChanged event for textboxes. It is quite easy to attach an event handler for textchanged.
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
And now, everytime we type something in the textbox or if we programmatically change the text, the event will get fired and we can display appropriate help message in the status bar or whatever we want.
Now, there may be specific scenarios where we don't want this event to be fired. For example, we want the event to be fired when the user type something, but we don't want the event to be fired when the text is changed programmatically.
This short sample shows how you can disable or suspend an event in .NET using C# syntax. The sample code assumes there is a textbox and a button created in a Winform. A text changed event is attached to the textbox. When the button is pressed, it will suspend the textchanged event and set some hardcoded text in the textbox. Then it will resume the textchanged event so that the event will be fired again when user type something in the textbox.
Declare an EventHandler member field :
private EventHandler textChangedEventHandler;
In the contructor of the form, after calling 'InitializeComponent()' create a new eventhandler and attach to the textchanged event.
textChangedEventHandler = new System.EventHandler(this.textBox1_TextChanged); this.textBox1.TextChanged += textChangedEventHandler;
If you have double clicked the textbox to create the textchanged event handler, VS.NET would have automatically added the below line in your 'InitializeComponent()' method. You may want to delete that line.
Now in your button clicked event, write the following code:
this.textBox1.TextChanged -= textChangedEventHandler; this.textBox1.Text = "Text changed event is not raised."; this.textBox1.TextChanged += textChangedEventHandler;
The first line will suspend or un subscribe the textchanged event handler. Second line will change the text for the textbox but the textchanged eventhandler will not be fired, because we unsubscribed it. The third line will again activate the textchanged event handler so that when user type anything in textbox, textchanged event will be fired.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|