Clear all TextBoxes on a Form

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This is a tutorial on how to clear all TextBoxes on a form in Visual Basic .NET.

Instead of calling each TextBox by its name and clear them one by one, you can use a For Each loop that clears all the TextBoxes found on the form

clear all textboxes on a form in visual basic

Here is the code that clears all TextBoxes text on a form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim a As Control
        For Each a In Me.Controls
            If TypeOf a Is TextBox Then
                a.Text = Nothing
            End If
        Next
    End Sub

You can also specify textboxes in a groupbox to be cleared. In the following example we will clear all textboxes in GroupBox1 only

clear all textboxes in a groupbox in visual basic .net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim a As Control
        For Each a In Me.GroupBox1.Controls
            If TypeOf a Is TextBox Then
                a.Text = Nothing
            End If
        Next
    End Sub

You can do more than just clearing the TextBoxes in the above For Each Loops

For example you can change the background color of all the textboxes in GroupBox1, change their text, font size, etc..


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2014 - All Rights Reserved.