我正在尝试使用字符串作为对象名称。示例我有一个对象,名称= Label1。我可以这样做吗?
Dim i As String = "Label1"
someVariable = i.Text
我使用字符串作为对象名称,是否可能?
答案 0 :(得分:2)
这是不可能的 - 但你能做什么:
Dim i As String = "Label1"
Dim Obj as Label
for each elem in me.controls
if elem.Name = i then
Obj = elem
exit for
end if
next
someVariable = obj.Text
我正在迭代所有WinForms控件以找到名称为“Label1”的标签 - 找到后,我将标签分配给变量。 这可行,但可能非常危险,特别是如果你添加控件
答案 1 :(得分:2)
你可以像@Christian Sauer所说的那样遍历所有控件,但如果任何控件是控件的容器,你可能会遇到问题。你需要做一个递归搜索来解决这个问题。但是,ControlCollection
实际上有一个Find()
方法可以使用。它返回一个与名称匹配的控件数组,并可选择执行递归搜索。
''//Our final control
Dim someVariable As Control = Nothing
''//Search recursively for our control
Dim SearchedControls = Me.Controls.Find(key:="Label1", searchAllChildren:=True)
''//If we found one and only one control
If SearchedControls.Count = 1 Then
''//Set it to our variable
someVariable = SearchedControls(0)
Else
''//Whatever your logic dictates here
End If
答案 2 :(得分:1)
我知道它已被回答,但这是我的图书馆,我一直都在使用它。它将以@ChrisHaas建议的方式递归遍历所有控件和容器的控件。
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
<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
(以前有人问过并回答过) Loop Through Controls on Web User Control
答案 3 :(得分:0)
我确定已经回答,但有些要点清楚它的控制阵列和结果,以确保它已得到纠正。
Private Sub btn1_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn1.Click
Dim Ds As New DataSet
Dim str As String = ""
str = " SELECT TOP (10) t_Suppliers.STNo from t_Suppliers "
Ds = SqlHelper.ExecuteDataset(ConnectionString, CommandType.Text, str)
For i As Integer = 0 To Ds.Tables(0).Rows.Count - 1
Dim str1 As String = "lblInv" & i + 1
Dim OBj As New Label
Try
Dim SearchedControls() As Control = Me.Controls.Find(key:=str1, searchAllChildren:=True)
If SearchedControls.Length > 0 Then
SearchedControls(0).Text = Ds.Tables(0).Rows(i).Item("STNo").ToString
End If
Catch
End Try
Next
End Sub
答案 4 :(得分:0)
我在另一个网站上找到了以下解决方案。 它有效。
--引用-
Dim TextBox As TextBox
Dim I As Integer = 2
Dim name As String = "TextBox" & I.ToString
TextBox = Me.Controls.Item(name)
TextBox.Text = "Something special"