2011-03-31 3 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- of-a-vb6-control-array 및 http://stackoverflow.com/questions/5738092/vb6-control-arrays-in-net – MarkJ

답변

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

+0

답변을 주셔서 감사합니다. :) :) –

+0

@vsdev VB6에서는 컨트롤을 일반 배열에 배치 할 수 없었습니다. –

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

아, 사실 수 있습니다. –

+0

코드를 사용하여 각 버튼에 텍스트를 지정하는 방법은 무엇입니까? –

+0

@Konrad Rudolph : 어떻게? – Anuraj

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