使用字符串作为对象名称 [英] Using string as object name

查看:36
本文介绍了使用字符串作为对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use string as object name. Example I have an object and has a name = Label1. Can I do this?

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

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

I'm using string as object name, is it possible?

推荐答案

您可以像@Christian Sauer 所说的那样迭代所有控件,但如果任何控件是控件的容器,您可能会遇到问题.你需要做一个递归搜索来解决这个问题.但是,ControlCollection 实际上有一个 Find() 方法,您可以使用.它返回与名称匹配的控件数组,并可选择执行递归搜索.

You could iterate over all of the controls as @Christian Sauer said but you might run into problems if any controls are containers of controls. You'd need to do a recursive search to solve that. However, the ControlCollection actually has a Find() method that you can use. It returns an array of controls that match the name and optionally performs a recursive search.

    ''//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

这篇关于使用字符串作为对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆