开发者

Clearing all RichTextBoxes from a form (VB.NET)

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

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

Thanks for any help. :)


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.


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


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
}


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜