views:

60

answers:

2

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?

+2  A: 

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.

David in Dakota
+1 beat me by 10 secs
Shiraz Bhaiji
A: 
For Each control In form.Controls
    If TypeOf control Is TextBox Then
        CType(control, TextBox).Clear()
    End If
Next
Darin Dimitrov