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

后端 未结 9 1727
时光取名叫无心
时光取名叫无心 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 04:09

    There are two aspects.

    .NET readily supports arrays of controls, VB6 just had to use a workaround because otherwise, wiring up events was really hard. In .NET, wiring up events dynamically is easy.

    However, the .NET form designer does not support control arrays for a simple reason: arrays of controls are created/extended at run time. If you know how many controls you need at compile time (the reasoning goes) then you give them different names and don't put them in an array.

    I know it's not very useful code

    That's exactly the point. Why have a feature if it's useless?

    If needed, you can also access a control by name, resulting in something like this:

    Private Sub Command_Click(sender As Object, e As EventArgs) Handles Command1.Click, Command2.Click …
        Dim name As String = DirectCast(sender, Control).Name
        Dim index As Integer = Integer.Parse(name.Substring("Command".Length))
        Controls(String.Format("Text {0}", index)).Text = Timer.Value.ToString()
    End Sub
    

提交回复
热议问题