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

后端 未结 9 1600
时光取名叫无心
时光取名叫无心 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
    
    0 讨论(0)
  • 2020-12-11 04:10

    Another nice thing that VB .NET does is having a single event handler that handles multiple controls:

    Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
            Handles TextBox1.TextChanged, _
    
            TextBox2.TextChanged, _
    
            TextBox3.TextChanged
    
    End Sub
    
    0 讨论(0)
  • 2020-12-11 04:10

    The same click event can handle the button presses from multiple buttons in .Net. You could then add the the text box to find in the Tag property?

    Private Sub AllButton_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
      Dim c As Control = CType(sender, Control)
      Dim t As TextBox = FindControl(CType(c.Tag, String))
      If t Is Not Nothing Then
         t.Text = "Clicked"
      End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题