2

我正在尝试使用字符串作为对象名称。示例 我有一个对象,并且有一个名称 = Label1。我可以这样做吗?

Dim i As String = "Label1"
someVariable = i.Text

我使用字符串作为对象名称,可以吗?

4

5 回答 5

3

正如@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
于 2013-03-11T13:41:29.633 回答
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”的标签 - 找到后,我将标签分配给变量。这可行,但可能非常危险,特别是如果您添加控件

于 2013-03-11T13:16:55.260 回答
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

(之前有人问过并回答过) Web User Control 上的循环控制

于 2013-03-11T15:18:11.663 回答
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
于 2015-02-27T00:35:09.877 回答
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"
于 2021-05-09T03:40:05.520 回答