VB.Net Loop通过使用变量的名称进行控制 [英] VB.Net Loop controls by names using variables

查看:138
本文介绍了VB.Net Loop通过使用变量的名称进行控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置一些控件的文本.

I need to set text of some controls.

我有一个Form,其中有一些CheckBoxes和一些TextBoxes.

I have a Form with some CheckBoxes an some TextBoxes.

VBA中(如果我有5个名为"TextBox1","TextBox2",..."TextBox5"的文本框),我可以使用类似这样的东西:

In VBA (If I have 5 TextBoxes named "TextBox1", "TextBox2", ... "TextBox5") I can use something like this:

For n = 1 To 5
    Me("TextBox" & n).Text = NeededValue 
Next n

我知道在VB.Net中也可能出现类似的情况,但是我找不到正确的语法(而且我也没有在SO上找到类似的代码).

I know that something like this is also possible in VB.Net but I wasn't able to find the right syntax (and I didn't find similar codes on SO).

我尝试使用

Me.Controls() 

但是我不能以这种方式插入控件名称

But I can't insert control name this way

推荐答案

使用For Each,然后使用TypeOf进行测试,以找到form中的所有TextBoxes,例如:

Use For Each and then test with TypeOf to find all TextBoxes in your form like :

For Each myObject1 As [Object] In Me.Controls
     If TypeOf myObject1 Is TextBox Then
         TryCast(myObject1, TextBox).Text = "NeededValue"
     End If
Next

也:

 Dim myText = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5}
        For Each btn In myText
            btn.Text = "NeededValue"
        Next

For i As Int32 = 1 To 5
    Dim Txt = Me.Controls.Find("TextBox" & i, True)
    If Txt.Length > 0 Then
        Txt(0).Text = "blah"
    End If
Next

或:

  For i As Int32 = 1 To 5
       Dim Txt = Me.Controls.Find("TextBox" & i, True)
         If Txt.Length > 0 Then
            Txt(0).Text = "NeededValue"
         End If
   Next

这篇关于VB.Net Loop通过使用变量的名称进行控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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