Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing an EventHandler (ComboBox)

Status
Not open for further replies.

Salte2

Programmer
Nov 5, 2004
17
NO
There is a ComboBox on my Windows Form. I have two different methods that are called when the Form is made visible, depending on what action the user intends to perform. In one case, i want the ComboBox to be tied to an EventHandler, and in the other case, i dont want it to be. So how can i make sure that the EventHandler is not triggered? Here are the two methods in question:
Code:
public void ShowFormWithEHandler()
{
cbx.SelectedIndexChanged += new EventHandler(TypeValgt);
ShowDialog();
}

public void ShowFormWithoutEHandler()
{
<?????>
ShowDialog();
}

What do i put where the ????? are now (to remove the eventhandler that might have been added previously)? And will the "+=" in the first method give me problems (it might be executed several times).
 
1) If you truely do not want the event fired, I would track this in the VisibleChanged event and use a module level boolean to track the status.

Code:
//This is at the module level
private bool m_blnShowFormWithEHandler = true;

private void Form_VisibleChanged(EventArgs evt) {
//Do not deal with the event handler at all
//unless the flag is set
if (m_blnShowFormWithEHandler) {
   if (this.Visible) {
      //Enable the event handler when the form is shown
      cbx.SelectedIndexChanged += new EventHandler(TypeValgt);
   } else {
      //Remove the event handler after the form is hidden
      //because the event will fire multiple times if it
      //is added several times without being removed
      cbx.SelectedIndexChanged -= new EventHandler(TypeValgt);
}

public void ShowFormWithEHandler()
{
m_blnShowFormWithEHandler = true;
ShowDialog();
}

public void ShowFormWithoutEHandler()
{
m_blnShowFormWithEHandler = false;
ShowDialog();
}

2) The easier and less risky approach would be to always fire the event but use a module level boolean to ignore or enable the event.

Code:
//This is at the module level
private bool m_blnShowFormWithEHandler = true;

private void cbx_SelectedIndexChanged(EventArgs evt) {
if (m_blnShowFormWithHandler) {
   //Do stuff here
}
}

public void ShowFormWithEHandler()
{
m_blnShowFormWithEHandler = true;
ShowDialog();
}

public void ShowFormWithoutEHandler()
{
m_blnShowFormWithEHandler = false;
ShowDialog();
}
 
Thank you very much dalchri. That is very helpful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top