vb.net 以编程方式向表单添加控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3199629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:56:00  来源:igfitidea点击:

Programmatically add controls to form

vb.net

提问by madlan

I'm using the attached code to add another line\row of controls beneath an existing set (when a label is clicked). There could be quite a few rows added so I'm having to repeat the code many times using the counter (i) to keep track...

我正在使用附加的代码在现有集下方添加另一行\行控件(单击标签时)。可能添加了很多行,因此我不得不使用计数器 (i) 多次重复代码以跟踪...

Is there a better method for doing this?

有没有更好的方法来做到这一点?

Private Sub Label10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)      Handles LblExpandSearch.Click
    If i = 0 Then

        'TextBox7
        '
        Dim TextBox7 As New TextBox
        TextBox7.Size = New Size(302, 20)
        TextBox7.Name = "TextBox7"
        TextBox7.Location = New System.Drawing.Point(60, 135)
        Me.ExpAdvancedSearch.Controls.Add(TextBox7)

        'RadioButton5
        '
        Dim RadioButton5 As New RadioButton
        RadioButton5.AutoSize = True
        RadioButton5.Checked = True
        RadioButton5.Location = New System.Drawing.Point(77, 112)
        RadioButton5.Name = "RadioButton5"
        RadioButton5.Size = New System.Drawing.Size(55, 17)
        RadioButton5.TabIndex = 48
        RadioButton5.TabStop = True
        RadioButton5.Text = "NEAR"
        RadioButton5.UseVisualStyleBackColor = True

    ElseIf i = 1 Then

        ExpAdvancedSearch.Size_ExpandedHeight = 260

        'TextBox8
        '
        Dim TextBox8 As New TextBox
        TextBox8.Size = New Size(302, 20)
        TextBox8.Name = "TextBox8"
        TextBox8.Location = New System.Drawing.Point(60, 185)
        Me.ExpAdvancedSearch.Controls.Add(TextBox8)


        'RadioButton9
        '
        Dim RadioButton9 As New RadioButton
        RadioButton9.AutoSize = True
        RadioButton9.Checked = True
        RadioButton9.Location = New System.Drawing.Point(77, 162)
        RadioButton9.Name = "RadioButton9"
        RadioButton9.Size = New System.Drawing.Size(55, 17)
        RadioButton9.TabIndex = 48
        RadioButton9.TabStop = True
        RadioButton9.Text = "NEAR"
        RadioButton9.UseVisualStyleBackColor = True

    End If

    i = i + 1
End Sub

回答by FastAl

Hmmm.. UseVisualStyleBackColor says 'winforms' to me.

嗯.. UseVisualStyleBackColor 对我说“winforms”。

A few points...

几点...

Don't add controls all to one panel, use a usercontrol.

不要将控件全部添加到一个面板,请使用用户控件。

Then just add instances of that.

然后只需添加它的实例。

Don't process click events from a label

不要处理来自标签的点击事件

Use a linklabel or button. Anything else = being mean to users. Of course it makes sense to you, you thought of it! Now so with users, this is black and white.

使用链接标签或按钮。其他任何东西 = 对用户来说都是刻薄的。当然对你有意义,你想到了!现在对于用户来说,这是黑白分明的。

Sample...

样本...

Very minimal of course. You'll want to:

当然非常少。你会想要:

  • Put the items in a scrollable panel instead of right on the form.
  • Add them to a generic list of uc probably, too.
  • Set form's min/max size - to allow reasonable sizing (allow any height > ~100)
  • Set uc's and controls .Anchor properties to allow reasonable resizing
  • 将项目放在可滚动面板中,而不是直接放在表单上。
  • 也可能将它们添加到 uc 的通用列表中。
  • 设置表单的最小/最大尺寸 - 允许合理的尺寸(允许任何高度 > ~100)
  • 设置 uc 和控件 .Anchor 属性以允许合理调整大小

uc.vb

uc.vb

Public Class uc
    Inherits System.Windows.Forms.UserControl

    Private components As System.ComponentModel.IContainer
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents LinkLabel1 As System.Windows.Forms.LinkLabel

    Public Sub New()
        MyBase.New()

        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.LinkLabel1 = New System.Windows.Forms.LinkLabel
        Me.SuspendLayout()

        Me.TextBox1.Location = New System.Drawing.Point(8, 8)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(88, 20)
        Me.TextBox1.TabIndex = 0
        Me.TextBox1.Text = "TextBox1"

        Me.LinkLabel1.Enabled = False
        Me.LinkLabel1.Location = New System.Drawing.Point(112, 8)
        Me.LinkLabel1.Name = "LinkLabel1"
        Me.LinkLabel1.Size = New System.Drawing.Size(24, 16)
        Me.LinkLabel1.TabIndex = 1
        Me.LinkLabel1.TabStop = True
        Me.LinkLabel1.Text = "add"

        Me.Controls.Add(Me.LinkLabel1)
        Me.Controls.Add(Me.TextBox1)
        Me.Name = "uc"
        Me.Size = New System.Drawing.Size(148, 36)
        Me.ResumeLayout(False)

    End Sub

    Private _addcallback As EventHandler = Nothing
    Public Property AddCallback() As EventHandler
        Get
            Return _addcallback
        End Get
        Set(ByVal Value As EventHandler)

            _addcallback = Value
            LinkLabel1.Enabled = Not Value Is Nothing

        End Set
    End Property

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        If AddCallback Is Nothing Then Throw New ApplicationException("AddCallback not set on a uc") ' ALWAYS check for errors like this 
        _addcallback(Me, Nothing)
        AddCallback = Nothing ' gray myself out, can't insert in thie implementation
    End Sub
End Class

frm.vb

窗体

Public Class frm
    Inherits System.Windows.Forms.Form

    Private components As System.ComponentModel.IContainer
    Public Sub New()
        MyBase.New()
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Name = "Form1"
        Me.Text = "Form1"
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddClicked(Me, Nothing)
    End Sub

    Private Sub AddClicked(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim myuc As New uc
        myuc.AddCallback = AddressOf AddClicked
        If Controls.Count > 0 Then
            myuc.Top = Controls(Controls.Count - 1).Bottom
        End If
        Me.Controls.Add(myuc)
    End Sub
End Class

回答by Chase Florell

I don't know if there's a "less code" approach to this but I do know that you can save your fingers using a Withstatement.

我不知道是否有一种“更少的代码”的方法来解决这个问题,但我知道你可以使用With语句来节省你的手指。

    Dim RadioButton5 As New RadioButton
    With RadioButton5
        .AutoSize = True
        .Checked = True
        .Location = New System.Drawing.Point(77, 112)
        .Name = "RadioButton5"
        .Size = New System.Drawing.Size(55, 17)
        .TabIndex = 48
        .TabStop = True
        .Text = "NEAR"
        .UseVisualStyleBackColor = True
    End With

回答by Chase Florell

If you need to add an indefinite number of items to a single page, then you need to store those items in an array list that we can later add to the page dynamically.

如果您需要向单个页面添加无限数量的项目,那么您需要将这些项目存储在一个数组列表中,以便我们稍后可以动态添加到页面中。

Imports System.Collections.Generic


Partial Class Default2
    Inherits System.Web.UI.Page

    ''# the i integer is here for helping to set the ID of the radio button 
    ''# as well as the tabindex
    Private Shared _i As Integer
    Public Shared Property i As Integer
        Get
            Return _i
        End Get
        Set(ByVal value As Integer)
            _i = value
        End Set
    End Property

    ''# we need to create an array of our control list class
    Public Shared _ctrlList As List(Of ControlList)





    ''# page load event
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            ''# if the page is not a postback, then we need to initialize the Control List
            _ctrlList = New List(Of ControlList)
            i = 0
        End If
    End Sub



    ''# button click event
    Protected Sub button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button.Click

        ''# create a new RadioButton every time the button is clicked
        Dim rb As RadioButton = New RadioButton
        With rb
            .ID = "radioButton" + i.ToString
            .Checked = True
            .TabIndex = 48 + i
            .Text = "NEAR"
        End With

        ''# create a new literal every time the button is clicked
        Dim lt As Literal = New Literal
        With lt
            .ID = "literal" + i.ToString
            .Text = " <strong>my fancy text</strong><br />"
        End With

        ''# add the radio button and literal to our custom array
        _ctrlList.Add(New ControlList(rb, lt))

        ''# loop through the array and add the controls to the page
        For Each cl In _ctrlList
            LabelPlaceHolder.Controls.Add(cl.RadioBtn)
            LabelPlaceHolder.Controls.Add(cl.Litrl)
        Next

        ''# increment the i counter so that we have unique radioButton ID's
        i = i + 1
    End Sub



    ''# this is our custom Control List
    ''# the idea behind this is for us to store 
    ''# an array of Radio Buttons and literals to 
    ''# spit out onto the page
    ''# NOTE: you can add as many controls as you like 
    ''# to this list and even add static "Literals" to 
    ''# help you with your formatting (IE: DIV tags or <BR> tags
    Public Class ControlList
        Private _RadioBtn As RadioButton
        Public Property RadioBtn As RadioButton
            Get
                Return _RadioBtn
            End Get
            Set(ByVal value As RadioButton)
                _RadioBtn = value
            End Set
        End Property

        Private _Litrl As Literal
        Public Property Litrl As Literal
            Get
                Return _Litrl
            End Get
            Set(ByVal value As Literal)
                _Litrl = value
            End Set
        End Property

        Public Sub New(ByVal radioBtn As RadioButton, ByVal litrl As Literal)
            _RadioBtn = radioBtn
            _Litrl = litrl
        End Sub

    End Class


End Class

Try this and see how it works. All you need in your ASPX is

试试这个,看看它是如何工作的。您在 ASPX 中所需要的只是

<form id="form1" runat="server">
    <asp:PlaceHolder runat="server" id="LabelPlaceHolder" /><br />
    <asp:Button ID="button" runat="server" Text="click me" />
</form>

Basically what this does is add an additional control set to the page every time the button is clicked. You can have an indefinite number of controls on the page without adding any additional code.

基本上这样做是在每次单击按钮时向页面添加一个额外的控件集。您可以在页面上拥有无限数量的控件,而无需添加任何额外代码。