TextChanged Property

Jay1b

Contributor
Joined
Aug 3, 2003
Messages
640
Location
Kent, Uk.
Hi

I have a richtextbox with a textchanged event. This event fires when the text box is first loaded with data, understandably. This is the code:
Visual Basic:
    Private Sub rtfText_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rtfText.TextChanged
        bHasChanged = True
    End Sub

I dont want bHasChanged to be set to true, upon loading, just when the user changes something. This value is then checked upon closing, and uses it to determine whether to prompt about saving changes. I can solve this by having a 'bFirstLoad' like below:

Visual Basic:
    Dim bFirstLoad as boolean = True
    Private Sub rtfText_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rtfText.TextChanged
        If bFirstLoad Then
          bFirstLoad = False
        Else
          bHasChanged = True
        End If
    End Sub

This will solve the problem, but it just seem unprofessional to me, is there a better way of doing this?

Thanks.
 
Yes I am using 2005.

I did actually look at that event, but it still fired when the data was loaded (although apparently it shouldnt do accordingly to that link). However looking at it again made me spot the richtextbox.modified. After setting this to false after loading i can use this just like i was the bhaschanged variable, and it looks so much more readable as well!

So thank you :)
 
Glad you found it, and glad to learn about the new Modified property - I hadn't seen that before.

A more general solution to avoiding the "loading" flags you mention, at least something we've been using for a few years: early-out of an event if the form's active control isn't the sender.

Finally! A great use for "sender" when you're not sharing event handlers! Here's a sample - the syntax may be wrong, I'm a C# guy:
Visual Basic:
Private Sub rtfText_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rtfText.TextChanged
        If Me.ActiveControl != sender Then Exit Sub
End Sub

-ner
 
Maybe I'm missing something, but why can't you store the original RTF? When the application closes or a new document is opened compare the current RTF to the original RTF and if they are not equal ask the user if he would like to save.
 
Back
Top