vb6 control arrays in .net?

淺唱寂寞╮ 提交于 2019-11-29 11:12:44

A "straight conversion" is not possible, but you can create control arrays in a different way: Creating Control Arrays in Visual Basic .NET and Visual C# .NET

VB.NET has no trouble with arrays of controls. The only thing that's missing is that the designer doesn't support them. Easily worked around with code. Like this:

Public Class Form1
    Private TextBoxArray() As TextBox

    Public Sub New()
        InitializeComponent()
        TextBoxArray = New TextBox() { TextBox1, TextBox2, TextBox3 }
    End Sub

End Class

You can have arrays of controls but they are not as built in as control arrays were in vb6. You can however create arrays of controls or have a unified event handlers similar to vb6.

I think I found the solution, I'm not the only former VB6 developer who has struggled with this limitation. A long time ago, I tried to migrate a software, but I failed because it had a tough dependency of control arrays. I read many forums and I was able to write this simple code:

Public Class Form1

'To declare the List of controls
Dim labels As New List(Of Label)()

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'To get all controls in the form
    For Each control In Me.Controls
        'To search for the specific type that you want to create the array 
        If control.[GetType]().Name.Contains("Label") Then
            'To add the control to the List
            labels.Add(DirectCast(control, Label))
        End If
    Next
    'To sort the labels by the ID
    labels = labels.OrderBy(Function(x) x.Name).ToList()
End Sub
End Class

I used a List for convenient reasons, but with that code you can create in design time the controls that you need and while you keep the "index" as the last characters (label1, label2, ..., labelN)

Later, you can iterate them with the loop and add them in the blink of an eye. Next, you are going to be able to manipulate them from the object with labels(0), labels(1), etc.

I hope this piece of code, it's going to help more programmers in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!