使用Me.Controls关键字访问vb中的不同变量

时间:2013-09-02 06:14:22

标签: vb.net

 Dim name1,name2,name3
 Dim i
 for i = 1 to 3
 Me.Controls("name" & i) = i
 next

每当我尝试执行此代码时,我都会收到错误消息。可能是什么问题?

关于,

nandgate。

2 个答案:

答案 0 :(得分:1)

您尝试将Integer分配给包含Control的集合的成员,可能除了没有名为name1name2的控件或表单上的name3。如果它有助于理解,那么您不会访问在第一个语句中声明的类型Object的三个变量:Me.Controls属性检索当前表单中的控件集合(假设此代码位于表单类中的某个位置)。

您似乎缺少一些概念,包括强类型和WinForms中常见类的结构,例如Control。我建议您从官方MSDN walkthrough开始。

答案 1 :(得分:0)

在我看来,您有兴趣获得一个控件说TextBox1并为其Text属性分配一些值。以下示例可以帮助您:

未经测试的示例代码:

 Dim name1,name2,name3
 Dim i
 for i = 1 to 3
   Dim ctrl() as Control = Me.Controls.Find("TextBox" & i, true)   ' Find control in all children controls
   if(ctrl isNot nothing andAlso ctrl.Length > 0) then ' if there is a control found
        Ctype(ctrl(0), Textbox).Text = i   ' Assign its text property to ith value.
   end if 
 next
相关问题