开发者

How to create controls from code using VB.NET?

开发者 https://www.devze.com 2022-12-23 22:15 出处:网络
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 Sy

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).

  1. Create test form. (Can be deleted once you extract the needed code from the designer code.)
  2. Add control/component to the test form.
  3. Set properties as needed.
  4. Open designer code and copy control's code.
  5. In actual form, create initialize method.
  6. Paste code into this method.
  7. If needed, create constructor for the actual form.
  8. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号