What's the simplest .NET equivalent of a VB6 control array?

后端 未结 9 1715
时光取名叫无心
时光取名叫无心 2020-12-11 03:42

Maybe I just don\'t know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 03:50

    I know that my answer is quite late, but I think I found the solution. I'm not the only former VB6 developer who has struggled with this limitation of VS. Long ago, I tried to migrate a CRM that I designed, but I failed because I had a tough dependency of control arrays (hundreds in one form). I read many forums and I was able to write this simple code:

    VB.NET:

    'To declare the List of controls
    Private textBoxes As List(Of TextBox) = New List(Of TextBox)()
    
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
        'To get all controls in the form
        For Each control In Controls
    
            'To search for the specific type that you want to create the array 
            If control.[GetType]() = GetType(TextBox) Then
                textBoxes.Add(CType(control, TextBox))
            End If
        Next
    
        'To sort the labels by the ID
        textBoxes = textBoxes.OrderBy(Function(x) x.Name).ToList()
    End Sub
    

    C#:

    //To declare the List of controls
    private List textBoxes = new List();
    private void Form1_Load(object sender, EventArgs e)
    {
        //To get all controls in the form
        foreach (var control in Controls)
        {
            //To search for the specific type that you want to create the array 
            if (control.GetType() == typeof(TextBox))
            {
                //To add the control to the List
                textBoxes.Add((TextBox)control);
            }
        }
    
        //To sort the labels by the ID
        textBoxes = textBoxes.OrderBy(x => x.Name).ToList();
    }
    

    There are 3 points to take in consideration:

    1. A List will help you to emulate the large collection of controls.
    2. typeof(Control) will help you define the type of the control to add in the list.
    3. While you keep the "index" as the last character (textBox1, textBox2, ..., textBoxN) you can create a logical order.

    Example in design mode:

    Running:

    A similar logic could be potentially used in other technologies like WPF, ASP.NET (Web Forms) or Xamarin (Forms) -in my opinion-. I hope this piece of code is going to help more programmers in the future.

提交回复
热议问题