在Visual Basic 2010中使用变量字符串引用对象 [英] Referencing an object using a variable string in Visual Basic 2010

查看:128
本文介绍了在Visual Basic 2010中使用变量字符串引用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上的 Visual Basic 2010中,我在表单上有几组相似的对象(标签,进度条).在我的代码中,我有一些包含数据的集合,这些数据需要被推入每个数据的value/text属性中.

I have several sets of similar objects (labels, progress bars) on a form in Visual Basic 2010 on Windows. In my code, I have collections that contain data, which needs to be pushed into the value/text property of each.

我想获得一种类似于PHP的解决方案,因为我可以分配一些类似于以下内容的值:

I would like to get a solution similar to PHP in that I can assign values somewhat like:

For ID as Integer from 0 to count(collectionExample) lblExample{ID}.Text=collectionExample(variableID)

For ID as Integer from 0 to count(collectionExample) lblExample{ID}.Text=collectionExample(variableID)

...这样循环遍历,因此将每个不同的lblExample都更新为它们的相应值.

...and as such to loop through so each of the different lblExample's were updated to their corresponding value.

我遇到的问题是,我似乎无法使用变量来引用表单上的对象.我也尝试过使用

The issue I have come to is that I cannot seem to reference an object on the form using a variable. I have also tried using something like

CallByName("lblExample" + variableID, "Text", CallType.Set, exampleCollection(variableID)) ...但是,我仍然无法结合字符串和变量来引用对象.

CallByName("lblExample" + variableID, "Text", CallType.Set, exampleCollection(variableID))... however I still can't combine the string and variable to reference the object.

是否有任何通过结合字符串前缀和可变字符串标识符来引用VB2010中的对象的解决方案,类似于PHP的$ variable {$ variable}方法?

Windows平台

推荐答案

您可以使用字符串作为键,将每个控件添加到字典中.

You could add each of the controls to a dictionary, using a string as the key.

然后您可以使用字符串访问控件.

Then you can access the controls using the string.

这是一个简单的示例,用foreach循环替换for循环...

Here is a simple example, replace the for loop with you foreach loop...

也许有一种更清洁的方式将您的数据与控件相关联,例如将控件放入以整数(在您的示例中为ID)索引的集合中,但是您需要一个字符串!

There may be a cleaner way to associate you data with controls, like putting the controls in a collection indexed by an integer (ID in your example), but you asked for a string!

Public Class Form1

Dim ctrlDict As New Dictionary(Of String, Control)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ctrlDict.Add("label1", Label1)
    ctrlDict.Add("label2", Label2)

    For i As Integer = 1 To 2
        ctrlDict("label" & i).Text = "Test" & i
    Next
End Sub

End Class

这篇关于在Visual Basic 2010中使用变量字符串引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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