开发者

Unwanted Retriggering of Textbox Events

开发者 https://www.devze.com 2023-01-01 07:45 出处:网络
This is one of t开发者_C百科hose \"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 t

This is one of t开发者_C百科hose "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?


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;
       }
   }
}


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.


Dim bUpdating As Boolean = False 
Private 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 If 
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消