我有64个面板,每个面板包含两个数据字符串。出于测试目的,我使用随机数生成器来提供我的数据。
我创建了一个字符串列表(总共64个字符串,包含“,”,每个面板分隔两个数据),现在需要将它们写入每个标签。
我需要找到一种方法来分割字符串数据(我知道如何)并写入每个标签。
例如:第一个字符串将被拆分并添加到名为Label1a和Label1b的第一个面板中,第二个字符串将拆分为Label2a和Label2b等。
Dim LotData As New List(Of String)
Dim randomnumber1 As Integer, randomnumber2 As Integer, randomchance As Integer
Dim slotnumber As String
Dim sbailes As String
Dim stemp As String
Randomize()
Dim n As Integer
For n = 1 To 64
randomnumber1 = CInt(Rnd() * 1000000000)
randomnumber2 = CInt(Rnd() * 300)
randomchance = CInt(Rnd() * 1000)
slotnumber = Convert.ToString(randomnumber1)
'approximately 50% of the lots will be empty in this test
If randomchance >= 500 Then
sbailes = CStr(randomnumber2)
Else
sbailes = "0"
End If
LotData.Add(slotnumber & "," & sbailes)
Next
我唯一的解决方案是编写128行代码,手动添加每个字符串,但我知道必须有一个更好的解决方案...
答案 0 :(得分:0)
您希望通过字符串名称获取控件。我有一些方法可以帮助你做到这一点(把它们放在一个模块中)
<Extension()> _
Public Function ChildControls(ByVal parent As Control) As ArrayList
Return ChildControls(Of Control)(parent)
End Function
<Extension()> _
Public Function ChildControls(Of T)(ByVal parent As Control) As ArrayList
Dim result As New ArrayList()
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(ctrl)
result.AddRange(ChildControls(Of T)(ctrl))
Next
Return result
End Function
Public Function GetControlByName(ByRef parent As Control, ByVal name As String) As Control
For Each c As Control In parent.ChildControls
If c.Name = name Then
Return c
End If
Next
Return Nothing
End Function
然后在您的方法中,您可以按名称获取控件,具体取决于从1到64的整数,如下所示:
For i As Integer = 1 To 64
CType(GetControlByName(Me, "Label" & i.ToString() & "A"), Label).Text = _
LotData(i).Split(",").FirstOrDefault()
CType(GetControlByName(Me, "Label" & i.ToString() & "B"), Label).Text = _
LotData(i).Split(",").LastOrDefault()
Next
哦!您还可以通过执行以下操作来省去在设计时将所有控件添加到表单的麻烦:
For i As Integer = 1 To 64
Dim lblA As New Label()
Dim lblB As New Label()
lblA.Name = "Label" & i.ToString() & "A"
lblB.Name = "Label" & i.ToString() & "B"
' do something about Locations here
Me.Controls.Add(lblA)
Me.Controls.Add(lblB)
' you could even add them to your panel.controls
Next
(不要忘记异常处理)