且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Vb.net如何使用不同的类型创建一个控件数组,即textbox,combobox,checkbox ...基于某个值

更新时间:2023-10-12 19:43:40

你把一个控制数组调到没有尺寸。这是先前的错误。

但是你需要这个数组?它足以实例化你的控件并将其添加到Form的Control-collection中。



为了纠正你的代码(目前有错误的方法)我想了解目标的更多信息......



澄清后补充:

You dim a as Array of Control with no Dimension. That ist the Prior mistake.
But for what do you need this Array ? It's enough to instance your control and add it to the Form's Control-collection.

To correct your code (which has the wrong approach in the moment) I would like to know something more about the Goal ...

Additional after clarification :
Public Sub CreateControls (c As Integer())
        Dim l As Point

        For i As Integer = 0 To c.Length - 1
            l.Y = 50 + (3 * i - 2) * 40  ' your Control-Height
            l.X = 150

            If c(i) = ??? Then  ' <- add the right value for comparing here
                dim myTB as New TextBox
                myTB.Width = 400
                myTB.Height = 40
                myTB.Location = l
                myTB.Name = "TextBox"+i.toString  ' <- important for later accessing
                me.Controls.Add(myTB)

            Else  ' if c(i)= ???
                dim myCB as New ComboBox
                myCB.Width = 400
                myCB.Height = 40
                myCB.Location = l
                myCB.Name = "ComboBox"+i.toString  ' <- important for later accessing
                me.Controls.Add(myCB)
            End If
        Next
   End Sub


以下是工作示例对象组 - 此实例中的控件...

Here is an example of working with groups of objects - Controls in this instance...
Private controls As List(Of Control) = New List(Of Control)

Sub AddControls()

    controls.Add(New PictureBox)
    controls.Add(New TextBox)
    controls.Add(New Label)

End Sub


嗯,错误信息是明确的。你声明了数组

Well, the error message is clear. You declared the array
Quote:

Dim a As Control()

Dim a As Control()

但从未创建它。





声明

but never created it.


The statement

a = new Control(c.Length){}





无论如何,我会按照 Graeme_Grant 建议使用动态容器,比如 List

is missing in your code.

In any case, I would follow Graeme_Grant suggestion and use instead a dynamic container, like the List.