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
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:
List will help you to emulate the large collection of controls.typeof(Control) will help you define the type of the control to add in the list.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.