views:

30

answers:

2

This is one of those "seems obvious" as how to do, but came across interesting side effect in implementing. I'm trying to keep two text boxes syncronized when information is updated. In this example, I will be using txtStartDate and txtEndDate. If the txtStartDate is changed, then the txtEndDate should should be updated. Likewise, if the txtEndDate changes, I want the txtSartDate to be updated. The side effect I'm comming across is that when I set them up under the TextChanged event for both, the events seem to retrigger against each other indefinately (endless loop?). Am I using the wrong event? Is this a task for a delegate?

A: 

A very basic way of solving it would be that you create an UpdateInProgress boolean member variable in the Form and at the start of each of the event handlers you check if it's true and if so you just ignore the event, otherwise set it to true and then set it to false at the end of the event.

ho1
+1  A: 

You need an extra condition. Depending on your setup, that could be "only change other value when I have focus".

A more general solution (I hope you can read C#):

private bool changingTextBox1 = false;
void textBox1TextChanged(object sender, EventArgs e)
{
   if (! changingTextBox1)
   {
       changingTextBox1 = true;
       try
       {
           // do stuff
       }
       finally
       {
          changingTextBox1 = false;
       }
   }
}
Henk Holterman
Yep, sure can. It works like a charm. Reposting the vb.net version for the record.<code>Dim bUpdating As Boolean = FalsePrivate Sub txtStartDate_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtStartDate.TextChanged If Not bUpdating = True Then bUpdating = True Try 'do stuff Catch ex As Exception Finally bUpdating = False End Try End IfEnd Sub</code>
hydroparadise
Hmm. Seems that replies don't handle tags?
hydroparadise
@hydroparadise: You can post that code as a separate answer. And then use the 001001 button to format code.
Henk Holterman