• Resetting text boxes on Visual Studio form

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Resetting text boxes on Visual Studio form

    Author
    Topic
    #472264

    I’m trying to use a button’s ‘click’ event to reset all the text boxes on my form. I’ve tried many iterations of the following:

    Code:
    Dim txt As Control
    For Each txt In Me.Controls
    
      If TypeOf txt Is TextBox Then txt.Text = ""
    
    Next

    It doesn’t do anything. If I substitute the clearing action with MsgBox(“test”), I still don’t get anything, so I feel like for some reason the code isn’t actually looking at the collection of controls on the form, but I don’t know how to fix it. I could simply list the 27 text boxes and set them all = Nothing, but that’s bad practice.

    Viewing 1 reply thread
    Author
    Replies
    • #1249205

      but that’s bad practice.

      I assume by your comment that you are using a variable/control naming convention. Thus why not try:

      Code:
      Dim txt As Control
      For Each txt In Me.Controls
      
        If Left$(txt.name,2) = "tb" Then txt.Text = ""
      
      Next

      or something similiar. Sorry, I can’t test this as I don’t have Visual Studio but logically it should work.

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1251652

      Jeremy,

      Your original code works just fine when I test it here (as does Retired Geek’s).

      If you’re substituting a simple MsgBox statement, and the message box doesn’t appear when you click the button, that doesn’t mean that the controls code isn’t working – it means that the code in the button Click procedure isn’t running at all.

      The most common cause for code in a button Click procedure to not run, is if the name of the button, as referenced in the procedure signature, is not identical to the actual name of the button.
      One way this can happen is if you create a new button – which gets a default name like CommandButton1 – and you then create a button click procedure for that button – so the procedure will be named “Private Sub CommandButton1_Click()”

      If you later go and rename the button to something meaningful like “cmdClearTextboxes”, but don’t change the name in the Click procedure’s signature, then the Click procedure code won’t run when you click the button.

      Any chance something like that is happening?

      Gary

    Viewing 1 reply thread
    Reply To: Resetting text boxes on Visual Studio form

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: