views:

327

answers:

4

I have a form with 25 RichTextBoxes. I need to clear them all when a user presses a button.

I think it's something to do with: Me.Controls.Clear but I'm not sure.

Thanks for any help. :)

+1  A: 

Me.Controls.Clear will remove all controls from the Controls collection. You need to iterate over all controls in Controls and if control is of type RichTextBox then call some clear method on that control.

see me no more
A: 

I think you could use linq to select all the textboxes... something like this (not tested and with a c# syntax)

IEnumerable<RichTextBox> txtBoxes = from txt in form1.Controls
                                where txt is RichTextBox
                                select (RichTextBox) txt;

then you can do a foreach loop clearing it.

foreach(RichTextBoxt in txtBoxes)
{
    // t.clear() ... clear(t) ... t.Text=String.empty ... o whatever you want
}
Jonathan
I think this skips any richtextboxes that are in a container on the form, rather than in the root of the form.
MarkJ
+1  A: 

You can do it this way. It clears all the textboxes on the form. If you want to save any richtextboxes, you can check ctl.name.

Dim ctl As Control
Dim rt As RichTextBox

For Each ctl In Me.Controls
  If TypeOf (ctl) Is RichTextBox Then
    rt = ctl
    rt.Clear()
  End If
Next ctl
xpda
A: 

Apparently any from ctrl in form.Controls... approach skips any (rich)textboxes that live within a panel/other container. This is also what MarkJ said in comment to Jonathan's answer.

Here's a routine to explicitly recurse over all controls and clear any control that (1) has no children, and (2) is a (rich)textbox.

Private Sub ClearControl(ByVal ctrl As Control)

    If ctrl.Controls.Count > 0 Then
        For Each subCtrl As Control In ctrl.Controls
            ClearControl(subCtrl)
        Next
    End If

    If TypeOf ctrl Is RichTextBox Then
        DirectCast(ctrl, RichTextBox).Clear()
    End If

    REM You can clear other types of controls in here as well
    If TypeOf ctrl Is TextBox Then
       DirectCast(ctrl, TextBox).Clear()
    End If

End Sub

Pass the form as the root control to start the recursion to clear all desired subcontrols: ClearControl(Me).

cfern