2012-02-15 23 views
0

有沒有任何方法將控件添加到VB.NET中的結構聲明中的容器?將控件添加到VB .NET中的結構聲明中的容器

我真的很想做的是:

Structure LabelContainer 
    Dim pnlContainer As New Panel 
    Dim lblTime As New Label 
    Dim lblStudent As New Label 
    Dim lblTeacher As New Label 
    lblTime.Parent = pnlContainer 
    lblStudent.Parent = pnlContainer 
    lblTeacher.Parent = pnlContainer 
End Structure 

但是,這並不在VB .NET工作。有沒有實現相同的事情?

+1

您不能將代碼放在結構聲明中。使用一個類,把代碼放在構造函數中。並拿起一本關於vb.net編程的書。 – 2012-02-15 03:38:19

回答

1

結構對控件所需事件的處理非常有限,例如創建控件時觸發的InitializeComponent()事件。有關詳細信息,請參閱本:

http://www.codeproject.com/Articles/8607/Using-Structures-in-VB-NET

你可以做的就是創建一個從面板繼承,而不是一類,例如:

Public Class LabelContainer 
    Inherits Panel 
    Friend WithEvents lblTeacher As System.Windows.Forms.Label 
    Friend WithEvents lblStudent As System.Windows.Forms.Label 
    Friend WithEvents lblTime As System.Windows.Forms.Label 

    Private Sub InitializeComponent() 
     Me.lblTime = New System.Windows.Forms.Label() 
     Me.lblStudent = New System.Windows.Forms.Label() 
     Me.lblTeacher = New System.Windows.Forms.Label() 
     Me.SuspendLayout() 
     ' 
     'lblTime 
     ' 
     Me.lblTime.AutoSize = True 
     Me.lblTime.Location = New System.Drawing.Point(0, 0) 
     Me.lblTime.Name = "lblTime" 
     Me.lblTime.Size = New System.Drawing.Size(100, 23) 
     Me.lblTime.TabIndex = 0 
     Me.lblTime.Text = "Label1" 
     ' 
     'lblStudent 
     ' 
     Me.lblStudent.AutoSize = True 
     Me.lblStudent.Location = New System.Drawing.Point(0, 0) 
     Me.lblStudent.Name = "lblStudent" 
     Me.lblStudent.Size = New System.Drawing.Size(100, 23) 
     Me.lblStudent.TabIndex = 0 
     Me.lblStudent.Text = "Label2" 
     ' 
     'lblTeacher 
     ' 
     Me.lblTeacher.AutoSize = True 
     Me.lblTeacher.Location = New System.Drawing.Point(0, 0) 
     Me.lblTeacher.Name = "lblTeacher" 
     Me.lblTeacher.Size = New System.Drawing.Size(100, 23) 
     Me.lblTeacher.TabIndex = 0 
     Me.lblTeacher.Text = "Label3" 
     Me.ResumeLayout(False) 

    End Sub 
End Class 
0

您可以將子添加到您的結構:

Structure LabelContainer 
    Dim pnlContainer As Panel 
    Dim lblTime As Label 
    Dim lblStudent As Label 
    Dim lblTeacher As Label 
    Sub AddControls() 
     lblTime.Parent = pnlContainer 
     lblStudent.Parent = pnlContainer 
     lblTeacher.Parent = pnlContainer 
    End Sub 
End Structure