Closed event fires twice

Hi All,

I have a form that is opened as a dialog (Form.ShowDialog). When I call Close() from within the form code the Closed event is fired twice... why

Here is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace LVDDataLogger
{
  public partial class FormLoopsChange : Form
  {
    private Station lvd;
    private int index;

    public bool ApplyAll = false;

    public FormLoopsChange(Station lvd, int index)
    {
      InitializeComponent();

      this.lvd = lvd;
      this.index = index;
      
      textBoxLoop.Text = String.Format("{0:d}", index + 1);
      comboBoxState.Items.Add(LoopState.Off);
      comboBoxState.Items.Add(LoopState.On);
      comboBoxState.SelectedIndex = (int)lvd.Loops[index].State;
      numericUpDownSensitivity.Value = lvd.Loops[index].Sensitivity;
      numericUpDownLength.Value = lvd.Loops[index].Length;
    }

    private void saveSettings()
    {
      //Get loop index
      if (checkBoxApplyAll.CheckState == CheckState.Unchecked)
      {
        lvd.Loops[index].State = (LoopState)comboBoxState.SelectedIndex;
        lvd.Loops[index].Sensitivity = (int)numericUpDownSensitivity.Value;
        lvd.Loops[index].Length = (int)numericUpDownLength.Value;
        this.ApplyAll = false;
      }
      else
      {
        foreach (Loop l in lvd.Loops)
        {
          l.State = (LoopState)comboBoxState.SelectedIndex;
          l.Sensitivity = (int)numericUpDownSensitivity.Value;
          l.Length = (int)numericUpDownLength.Value;
        }
        this.ApplyAll = true;
      }
    }

    private void menuItemOK_Click(object sender, EventArgs e)
    {
      //Save
      saveSettings();
      //Indicate values changed
      this.DialogResult = DialogResult.OK;
      this.Close();
    }

    private void menuItemCancel_Click(object sender, EventArgs e)
    {
      //Indicate values not changed
      this.DialogResult = DialogResult.Cancel;
      this.Close();
    }

    private void FormLoopsChange_Closed(object sender, EventArgs e)
    {
      MessageBox.Show("Closed event!");
    }
  }
}


Answer this question

Closed event fires twice

  • Akheiran

    If you are showing your form via a call to ShowDialog, setting the dialog result (this.DialogResult = DialogResult.OK) will be enough to close the form for you. The additional call to this.Close() after setting the dialog result is what is triggering the second close event to get fired.

  • flrzeus

    just as a point to note.
    you may be better of using the From_closing event



  • Kartik

    Thanks!
  • Closed event fires twice