How to Detect Textbox Change-VBForums
Results 1 to 16 of 16

Thread: How to Detect Textbox Change

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    How to Detect Textbox Change

    The Textbox_TextChanged event fires when a key is pressed or when text is pasted while cursor is in a text box.

    Is there an event that fires on Textbox1.text="NewText"? How do I detect this?

    My reason for doing this is I would like to reformat text property automatically on assignment rather than do something like textbox.text=myreformat("Newtext")

    I can put code in validating or validated event but then I'd have to force focus/lostfocus to trigger one of those events.

    Any suggestions?

    Lee

  2. #2
    Addicted Member Mr.Joker's Avatar
    Join Date
    Apr 2012
    Posts
    140

    Re: How to Detect Textbox Change

    Just make a statement:

    vb.net Code:
    1. If TextBox1.Text = "New Text" Then
    2. 'Code to do
    3. End If

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    Need to do this as a textbox Event.
    Also, forgot to mention that I can't use the TextChanged event cuz that fires on every key stroke.
    Need an event that fires on assignment.

    LB

  4. #4
    Addicted Member Mr.Joker's Avatar
    Join Date
    Apr 2012
    Posts
    140

    Re: How to Detect Textbox Change

    It shouldnt run everytime. The code I gived you above will be executed only and only if textbox text have New Text writen inside. If it doesent it will never run. I can type forever then. Just double click on textbox and try this:

    vb.net Code:
    1. If TextBox1.Text = "New Text" Then
    2.             MessageBox.Show("You typed New Text in TextBox")
    3.         End If
    Then , you run application and type New Text. Only then event will run,

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    Joker:
    Yes, that does work if I know what user is assigning to Text property.
    I do not know what user will be entering as it could be a decimal variable, a date or maybe just text.
    I need this event to format entry for display.
    So, for example if a number is assigned, I might want to format it as currency before displaying it or if a date is assigned, format date as Long Date.

    lb

  6. #6
    Addicted Member Mr.Joker's Avatar
    Join Date
    Apr 2012
    Posts
    140

    Re: How to Detect Textbox Change

    If you tell me what excatly you want, and not examples I can give you the code. I cant type a code if you dont tell me what you really want to do. Just say "I want you give me a code that will make a number from textbox into text, or whatever". Ok?

  7. #7
    Member chipp's Avatar
    Join Date
    May 2012
    Posts
    55

    Re: How to Detect Textbox Change

    - if the textbox.text changed because of the user's input then we can check it using "TextChanged" method
    - if the text changed by the code, the you're the one who decide the next step, for example:
    vb.net Code:
    1. if textbox1.Text = "something" Then
    2.     '...
    3. End If

  8. #8
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: How to Detect Textbox Change

    Try making the event TextBox_Leave, so when you click out of the textbox it will run the code.

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    OK - Lets try this.
    Place 2 text boxes on a form and also a button.
    Add my code to the form.

    Enter 123 in textbox1 and press tab or click on textbox2 to terminate input.
    Notice that textbox1 has been reformatted to display currency $123.00

    Now, enter 456 in textbox2 and click button to set textbox1.text=textbox2.text

    Notice that textbox1 now shows 456 not $456.00 as I want.

    Must somehow have an event that responds to the assignment that executes the following:
    TextBox1.Text = Convert.ToDecimal(Decimal.Parse(TextBox1.Text, Globalization.NumberStyles.Currency)).ToString("c")

    Code:
    Public Class Form2
    
        Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            Dim DecSep As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
    
            If e.KeyChar = Chr(8) Then
                Exit Sub
            ElseIf Char.IsNumber(e.KeyChar) = False Then
                If e.KeyChar = DecSep Then
                    Exit Sub
                Else
                    e.Handled = True
                    Exit Sub
                End If
            End If
        End Sub
    
    
        Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
            Dim currency As Decimal
            'Convert the current value to currency, with or without a currency symbol.
            If Not Decimal.TryParse(TextBox1.Text, _
                                    Globalization.NumberStyles.Currency, _
                                    Nothing, _
                                    currency) Then
                'Don't let the user leave the field if the value is invalid.
                With TextBox1
                    .HideSelection = False
                    .SelectAll()
                    MessageBox.Show("Please enter a valid currency amount.", _
                                    "Invalid Value", _
                                    MessageBoxButtons.OK, _
                                    MessageBoxIcon.Error)
                    .HideSelection = True
                End With
                e.Cancel = True
            End If
        End Sub
    
        Private Sub TextBox1_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
            'Display the value as local currency.
            TextBox1.Text = Convert.ToDecimal(Decimal.Parse(TextBox1.Text, Globalization.NumberStyles.Currency)).ToString("c")
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TextBox1.Text = TextBox2.Text
        End Sub
    End Class

  10. #10
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    24,768

    Re: How to Detect Textbox Change

    Yeah, that's not going to happen...at least not automatically. The control knows when the text has changed, but it can't know HOW the text was changed. That would require the control to know about things beyond the object itself. I suppose it would be possible if the = operator was overloaded for the control such that it raised a different event when that operator was used, but I'm not sure that even that would work (after all, there has to be assignment somewhere in there whenever you type text into a control, and the operator would be overloaded for the contol, not just a property of the control). In any case, the operator isn't overloaded, so that's not an option.

    However, you can make your own event if you want to. whenever you assign to the textbox in code, raise the event. That's pretty much all you can do, because what you are really asking for is not nearly as distinct as you seem to think it is. You already have the event for TextChanged, and you already know the limitations of that event, but it is the only event possible. After all, when you are typing into a textbox, each character is coming in at any one time. Nobody types fast enough for those characters to appear as anything other than slow, character by character, entries. Pure tedium for the computer. Therefore, the computer can't really know when you are done entering text, which is why the validating and Leave and LostFocus events exist. The case you are looking at is when text is changed, but changed in a certain way, which may or may not be distinct.

    There are two things you might consider trying:

    1) Cache the value in the textbox. In the textChanged event, compare the new to the old. If the difference in the length is anything other than 1, do the formatting then. This would pick up most of the cases, but will fail noticeably in several situations (e.g. the textbox has 123.45 and you assign 123.456). You might try comparing the text between the two, but as you can see in that example, there is no way to distinguish between typing entry and assignment between those two.

    2) Watch the KeyDown event as well as TextChanged. If you get TextChanged without KeyDown, then entry was either by assignment or by copy and paste. If you get KeyDown AND TextChanged, then the entry was by typing. That may be a good enough distinction for your purposes. It may fail, also. I'm not sure whether Ctrl+P pasting would cause the KeyDown (it probably would), but you can exlcude that by checking the key combination.

    It's not all that easy, but the key point is that you have to be able to determine what is distinct about assignment vs typing. There isn't much that is distinct, but if you play around with it, there might be just barely enough to work with.
    My usual boring signature: Nothing

  11. #11
    vb Coda .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    19,282

    Re: How to Detect Textbox Change

    2\ alternatively, inherit the textbox + override the wndProc + capture the WM_PASTE message, along with overriding the onTextChanged event to test keyboard input

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    Paul:
    Don't understand a thing you said . How about a code example?

    On another note.... I see you're from Chelmsford - I had some friends that lived there in an old priory back in the 60's. I used to go there to visit them when I lived in London.

    Lee
    (Florida - USA)

  13. #13
    vb Coda .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    19,282

    Re: How to Detect Textbox Change

    ok. where's the priory?

    try this. add the class to your project. after rebuilding, you'll find the observableTextBox control at the top of your toolbox + you add it like any control:

    vb Code:
    1. Public Class observableTextBox
    2.     Inherits TextBox
    3.  
    4.     Const WM_PASTE As Integer = &H302
    5.  
    6.     Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
    7.         MsgBox("KeyPress")
    8.         MyBase.OnKeyPress(e)
    9.     End Sub
    10.  
    11.     Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    12.         If m.Msg = WM_PASTE Then
    13.             MsgBox("Paste")
    14.         End If
    15.         MyBase.WndProc(m)
    16.     End Sub
    17.  
    18. End Class

  14. #14

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    Paul:
    Thank you for the code example - however, it still does not identify an assignment. Paste or Keypress require that cursor is in the textbox and a subsequent "Validate" event is available to trigger the code required to reformat the displayed text. Validate is not fired on assignment unfortunately. Guess I'll just put formatting in a function and use textbox.text=myFormat(value) when I do an assignment.

    As far as the Priory, as I remember it was a house in town (short walk to pub) built in 17th century.
    It had a ceiling with exposed arched beams in reception area with minstrel gallery. Also I remember a huge fireplace in kitchen and wood paneled walls in the sleeping rooms. I seem to remember it was on Chelmsford Road or Bridge Street but that was 45 years ago and my memory isn't that good. The people living there were Americans who were working at Wethersfield Air Base.

    Cheers!

    Lee

  15. #15
    vb Coda .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    19,282

    Re: How to Detect Textbox Change

    i live closer to Maldon. did you ever go there? the whole place is stuck in the 17th century

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Posts
    94

    Re: How to Detect Textbox Change

    Wife has corrected me. Friends lived in Chelmsford originally then moved to Thaxted into the Priory.
    http://www.britishlistedbuildings.co...ory-38-thaxted.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.