VB.Net Loop通过使用变量的名称进行控制 [英] VB.Net Loop controls by names using variables
问题描述
我需要设置一些控件的文本.
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屋!