Bibhas Debnath
Bibhas Debnath

Reputation: 14929

WinForms Clearing multiple Textboxes with one command

I have several textboxes in a form, and have a button which inserts all the values in a Database and I have to clear the content of all the textboxes and focus to the first one right after pressing the button.

Now I can easily do that using the Clear method of each of the textboxes but it takes 10-12 lines of code just for that. Can I do that in one go?

Upvotes: 1

Views: 4095

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

For Each control In form.Controls
    If TypeOf control Is TextBox Then
        CType(control, TextBox).Clear()
    End If
Next

Upvotes: 0

t3rse
t3rse

Reputation: 10124

From your container (e.g. the Form), iterate through the controls collection and test whether a child is a TextBox. If so, cast it and then clear out the text. In VB.NET here is some code:

    For Each c As Control In Me.Controls
        If TypeOf c Is TextBox Then
            DirectCast(c, TextBox).Text = ""
        End If
    Next

You also can make a recursive version of this so that if you have controls that might contain other controls, they are processed as well.

Upvotes: 4

Related Questions