tags:

views:

51

answers:

1

I have the following method that is executing twice every time it is called:

public static void ChangeToRepository(RepositoryTextBox textBox, int repositoryNumber)
    {
        MessageBox.Show("you");
        int indexOfLastRepository = (textBox.RepositoryCollection.Count - 1);
        if (repositoryNumber > indexOfLastRepository)
        {
            AddTextRepositoriesThrough(textBox, repositoryNumber, indexOfLastRepository);
        }
        textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText = textBox.Text;
        textBox.PreviousRepositoryNumber = textBox.CurrentRepositoryNumber;
        textBox.CurrentRepositoryNumber = repositoryNumber;
        textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
    }

The first time that the method executes, it executes all of the code except for its last line:

textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;

The second time, it executes all of the code. What's up?

A: 

When you assign to CurrentRepositoryNumber on the text box, it probably triggers an event handler that calls back to this function again. This seems likely because the property name suggests that it controls the current repository, which this method then is responsible for displaying somehow.

You might want to temporary delist, assign to the property and then re-enlist that event handler. Or maybe you need more of a redesign to get the responsibilities clear - often with GUI frameworks that is hard to do, and the simplest option is to just delist, assign, re-enlist, with this kind of pattern:

textBox.TextChange -= YourHandler;
textBox.Text = newValue;
textBox.TextChange += YourHandler;
Daniel Earwicker
I had forgotten creating an OnCurrentRepositoryNumberChanged event which calls the ChangeToRepository method. Thanks.
Justin