对于每个Textbox循环返回控件的最后一个?

时间:2014-07-03 22:50:24

标签: vb.net

我在表单上有以下代码和9个文本框:

For Each ctrl As Control In Me.Controls
    If TypeName(ctrl) = "TextBox" Then
        If Not ctrl.Text.Length = 0 Then
            MsgBox(ctrl.Name)
        End If
    End If
Next

但是,如果例如填充了3个文本框,则生成的消息框将显示:

TextBox3
Textbox2
Textbox1

按顺序,从下到上。任何人都能解释为什么会这样做吗?是否有一种简单的方法可以让它们按顺序返回?

5 个答案:

答案 0 :(得分:2)

如果您希望订单从上到下,您可以这样排序:

For Each ctrl As TextBox In Me.Controls.OfType(Of TextBox).OrderBy( _
                                               Function(x) x.Top)
  If Not ctrl.Text.Length = 0 Then
    MsgBox(ctrl.Name)
  End If
Next

答案 1 :(得分:1)

你不能通过名称来确定顺序,你必须查看设计器文件才能真正看到谁是第一个。例如:

Me.Button1 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
'...
Me.Controls.Add(Me.Button7)
Me.Controls.Add(Me.Button6)
Me.Controls.Add(Me.Button5)
Me.Controls.Add(Me.Button4)

他们将“退出”似乎最后一个名字,但他们实际上是按照有意义的顺序进入集合,即 z-order

For Each ctl As Control In Controls
    Console.WriteLine(ctl.Name)
Next
TextBox2.BringToFront()
Console.WriteLine("new order:")
For Each ctl As Control In Controls
    Console.WriteLine(ctl.Name)
Next

输出:

TextBox3
TextBox2
TextBox1
new order:
TextBox2
TextBox3
TextBox1

您始终可以按名称获取控件引用,因此顺序并不重要:

thisBtn = CType(Controls("Button1"), Button)

如果您的代码以特定顺序处理某些控件很重要,您应该维护自己的列表 - 表示控件名称的List(Of String)或存储实际的List(Of TextBox)(例如)对象引用:

Private myTBList As New List(Of String)
...
myTbList.Add("TextBox13")
...etc

处理它们:

Dim TB As TextBox

For Each s As String In myTBList
    TB = CType(Controls(s), TextBox)
    If TB IsNot Nothing Then
        ' do something wonderful here
    End If
Next

答案 2 :(得分:0)

我认为你无法控制那个订单。而是创建一个字符串列表。存放 控制名称然后排序。相应地显示。

Dim list As List(Of String) = New List(Of String)

For Each ctrl As Control In Me.Controls
    If TypeName(ctrl) = "TextBox" Then
        If Not ctrl.Text.Length = 0 Then
            list.Add(ctrl.Name);
        End If
    End If
Next

list.Sort();

For Each element As String In list
    MsgBox(element)
Next

答案 3 :(得分:0)

订单由VB.NET预先确定。你可以设置。以相反的顺序BringToFront控件属性以纠正此功能。在您的示例中,首先单击TextBox3,然后在Format菜单中,选择Order并选择BringToFront。对TextBox2和TextBox1执行相同的操作。这并不优雅,但确实有效。

答案 4 :(得分:0)

试一试。它假定您不是在运行时添加控件。

Dim tbs As New List(Of TextBox)
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    'this will get all controls including those in
    'containers
    Dim ctrl As Control = Me.GetNextControl(Me, True)
    Do Until ctrl Is Nothing
        If TypeOf ctrl Is TextBox Then
            tbs.Add(DirectCast(ctrl, TextBox))
        End If
        ctrl = Me.GetNextControl(ctrl, True)
    Loop
    tbs = tbs.OrderBy(Function(tb) tb.Name).ToList
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each t As TextBox In (From tb As TextBox In tbs Where tb.TextLength > 0 Select tb)
        Debug.WriteLine(t.Name)
    Next
End Sub