2011-03-31 92 views
0

如何在VB.NET中爲按鈕創建控件數組?像在Visual Basic 6.0中一樣...VB.NET中的控件數組

語法是否可能如下所示?

dim a as button 

for each a as button in myForm 
    a.text = "hello" 
next 
+0

參見http://stackoverflow.com/questions/39541/whats-the-simplest-net-equivalent-一個vb6控制數組和http://stackoverflow.com/questions/5738092/vb6-control-arrays-in-net – MarkJ 2011-04-21 11:42:08

回答

2

.NET中的控件只是普通的對象,所以你可以自由地將它們放到普通的數組或列表中。控制陣列的特殊VB6結構不再是必需的。

所以你可以例如說,

Dim buttons As Button() = { Button1, Button2, … } 

For Each button As Button In Buttons 
    button.Text = "foo" 
End For 

或者,您可以通過直接控制遍歷一個容器內(如表格):

For Each c As Control In MyForm.Controls 
    Dim btt As Button = TryCast(c, Button) 
    If btt IsNot Nothing Then ' We got a button! 
     btt.Text = "foo" 
    End If 
End For 

請注意,這僅適用於控制那就是直接的形式;嵌套到容器中的控件不會以這種方式迭代;您可以使用遞歸函數遍歷所有控件。

+0

控制數組在VB中是不同的我認爲 – Anuraj 2011-03-31 09:06:18

+0

感謝您的答案.. :)它的作品..;) – 2011-03-31 09:09:25

+0

@vsdev它只是因爲必要性不同:VB6不允許將控制放入普通數組。 – 2011-03-31 09:24:11

1

你不能在VB.NET中創建一個控件數組,但你可以使用關鍵字Handles存檔類似的功能。

public sub Button_Click(sender as Object, e as EventArgs) Handles Button1.Click, Button2.Click, Button3.Click 
    'Do Something 
End Sub 

是的,你可以這樣做。但我不認爲你可以通過給myForm直接迭代按鈕。

+0

哦,其實你可以。 – 2011-03-31 09:01:55

+0

如何使用代碼爲每個按鈕分配文本? – 2011-03-31 09:03:45

+0

@Konrad魯道夫:怎麼樣? – Anuraj 2011-03-31 09:03:45

1

您創建一個表單並添加布局10 * 10,並嘗試這個,

Public Class Form1 
    Private NRow As Integer = 10 
    Private NCol As Integer = 10 
    Private BtnArray(NRow * NCol - 1) As Button 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     TableLayoutPanel1.Size = Me.ClientSize 
     For i As Integer = 0 To BtnArray.Length - 1 
      BtnArray(i) = New Button() 
      BtnArray(i).Anchor = AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right 
      BtnArray(i).Text = CStr(i) 
      TableLayoutPanel1.Controls.Add(BtnArray(i), i Mod NCol, i \ NCol) 
      AddHandler BtnArray(i).Click, AddressOf ClickHandler 
     Next 
    End Sub 
    Public Sub ClickHandler(ByVal sender As Object, ByVal e As System.EventArgs) 
     MsgBox("I am button #" & CType(sender, Button).Text) 
    End Sub 
End Class