我正在尝试遍历组框内的多个文本框控件。代码以相反的顺序将文本框值写入临时文件。
我有以下代码:
怎么了?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Temp.txt", False)
For Each item As Control In sourceGroupBox.Controls
If TypeOf item Is TextBox Then
If Len(item.Text) > 0 Then
file.WriteLine(item.Text)
End If
End If
Next
file.Close()
End Sub
答案 0 :(得分:2)
Controls集合不一定按任何特定顺序排列。但是,您可以利用LINQ按顺序获取它们:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Temp.txt", False)
For Each item As Control In sourceGroupBox.Controls.OfType(Of TextBox).OrderBy(Function(x) x.Name)
If Len(item.Text) > 0 Then
file.WriteLine(item.Text)
End If
Next
file.Close()
End Sub
这假定您使用2位数字为文本框提供了名称
答案 1 :(得分:-1)
你可以用id的for循环来做。
For id As Integer = 1 To 10
Dim item As TextBox = CType(sourceGroupBox.Controls("S" & id), TextBox)
If Len(item.Text) > 0 Then
file.WriteLine(item.Text)
End If
Next