How to create controls from code using VB.NET?
I 开发者_运维技巧want to know if I can create a WebBrowser through code in Vb.NET, instead of dragging a webbrowser into the form.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim browser As New WebBrowser
Controls.Add(browser)
End Sub
In general, if you want to know how to do from code what the Designer does, then create what you'd like using the Designer, then look in the .designer.vb (or .designer.cs) file.
To add what John Saunders mentions, I usually create the control through the designer in a test form, setting the properties of the control as needed. Then in the actual form, I create an Initialize method that gets called immediately after the InitializeComponent in the form's constructor.
This allows others to easily identify that I am creating the control manually and to easily locate the code for changes (since there is no designer).
- Create test form. (Can be deleted once you extract the needed code from the designer code.)
- Add control/component to the test form.
- Set properties as needed.
- Open designer code and copy control's code.
- In actual form, create initialize method.
- Paste code into this method.
- If needed, create constructor for the actual form.
- Call the intialize method.
WinForms Sample:
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
InitializeTagViewer()
InitializeRssPane()
InitializeAuditPane()
InitializeViewMenuItems()
#If DEBUG Then
InitializeDevelopmentMenu()
#End If
End Sub
Private Sub InitializeAuditPane()
Me.__auditPane = New AuditPane
Me.__lowerRightSplitContainer.Panel2.Controls.Add(Me.__auditPane)
'
'__auditPane
'
Me.__auditPane.Dock = System.Windows.Forms.DockStyle.Fill
Me.__auditPane.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.__auditPane.Location = New System.Drawing.Point(0, 0)
Me.__auditPane.Name = "__auditPane"
Me.__auditPane.Size = New System.Drawing.Size(150, 198)
Me.__auditPane.TabIndex = 0
End Sub
精彩评论