Search code examples
c#delegatesmessageboxformclosing

FormClosing delegate event problem


I have two forms named 'mainForm' and 'addRslt'. The idea is when users click on a button in mainForm, the addRslt form will Show() and then user will populate a TreeView. Now when user WANT to CLOSE this addRslt form, program will instead Hide() the form (using e.Cancel = true; ) so later if user reopen this he/she can add more things to the TreeView.

In my mainForm I have a button for showing this addRslt form, and also inside this button's click code, there is my FormClosing delegte which will detect and copy the contents od TreeView in addRslt form to a TreeView in mainForm.

Now the problem is I want to check for duplicated Nodes and do not add them to TreeView in mainForm. This is done right, but I also have a message box that tells the user that program had not added existing nodes! thats ok till now.. BUT problem is with each time I do this, this messagebox will appear N+1 times! I mean if I do it for first time, this message box appears 2 time and etc...

Here is my code! Sorry for long story!

    private void menuFileAddTestResults_Click(object sender, EventArgs e)
    {
        addRslt.Show();

        addRslt.FormClosing += delegate
        {
            foreach (TreeNode node in addRslt.treeViewSelectedFiles.Nodes)
            {
                TreeNode newNode = new TreeNode();
                newNode.Text = node.Text;
                newNode.Name = node.Name;
                newNode.Tag = node.Tag;

                if (!treeViewTestFiles.Nodes.ContainsKey(node.Name))
                {
                    treeViewTestFiles.Nodes.Add(newNode);
                }
                else
                {
                    countExist++;
                }
            }

            if (countExist > 0)
            {
                MessageBox.Show(countExist.ToString() + " Test files are already exist in the list!");
            }

            countExist = 0;
        };
    }

Solution

  • You're adding a FormClosing handler every time you show it. Just add it once, when you set up the rest of what the form looks like. (Personally I'd probably split this into a separate method... I don't think it's a particularly appropriate use of a lambda expression - it's a fairly large chunk of code which doesn't refer to any variables declared within the containing method, so there's no real benefit.)