Vb.net如何使用不同的类型创建一个控件数组,即textbox,combobox,checkbox ...基于某个值 [英] Vb.net how to create an array of controls with different types i.e textbox, combobox, checkbox...based on certain value
问题描述
这是代码:
This is the code:
Public Function TestControl(c As Integer())
Dim a As Control()
Dim l As Point
Dim F As New Form
For i As Integer = 0 To c.Length - 1
If c(i) Then
a(i) = New TextBox
Else
a(i) = New ComboBox
End If
a(i).Width = 400
a(i).Height = 40
l.Y = 50 + (3 * i - 2) * a(i).Height / 2
l.X = 150
a(i).Location = l
F.Controls.Add(a(i))
Next
F.Show()
Return Nothing
End Function
当我尝试执行该功能时,出现以下错误:
变量'a'在分配值之前使用。在运行时可能会产生空引用异常。
我尝试过:
我试图解决它,但我不能成功。任何想法都对我很有帮助
谢谢
When I am trying to execute the Function the following Error appears:
Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime.
What I have tried:
I am trying to solve it but i couldn't succeed. any Idea would very helpful for me
Thanks
推荐答案
你把一个控制数组调到没有尺寸。这是先前的错误。
但是你需要这个数组?它足以实例化你的控件并将其添加到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
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
.
这篇关于Vb.net如何使用不同的类型创建一个控件数组,即textbox,combobox,checkbox ...基于某个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!