vb.net 如何在 VB .NET 中创建控件数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5299435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:21:05  来源:igfitidea点击:

How to create Control Arrays in VB .NET

vb.netvb6

提问by vijay

In VB6 there is a feature called Control Arrays, where you name controls the same name and provide them an index value. This allows you to set a value by looping through the controls and setting each value. In VB .NET I can't create a control array could someone provide me with a similar solution.

在 VB6 中,有一个名为 Control Arrays 的功能,您可以在其中为控件命名相同的名称并为其提供索引值。这允许您通过循环浏览控件并设置每个值来设置值。在 VB .NET 中,我无法创建控件数组,有人可以为我提供类似的解决方案。

回答by dwidel

Here is a sample I wrote for something else that shows how to do something similar and shows how to do the handler as well. This makes a 10x10 grid of buttons that turn red when you click them.

这是我为其他东西编写的示例,它展示了如何做类似的事情并展示了如何做处理程序。这会生成一个 10x10 的按钮网格,当您单击它们时会变成红色。

Dim IsCreated(99) As Boolean
Dim Buttons As New Dictionary(Of String, Button)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    For i As Integer = 0 To 99
        Dim B As New Button
        Me.Controls.Add(B)
        B.Height = 30
        B.Width = 40
        B.Left = (i Mod 10) * 41
        B.Top = (i \ 10) * 31
        B.Text = Chr((i \ 10) + Asc("A")) & i Mod 10 + 1
        Buttons.Add(B.Text, B)
        B.Tag = i
        AddHandler B.Click, AddressOf Button_Click
    Next


End Sub

Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim B As Button = sender
    IsCreated(B.Tag) = True
    B.BackColor = Color.Red
End Sub

回答by Hans Passant

Avoid using the proposed iteration approaches, you'll get a fairly random collection of controls unless your form is very simple. Simply declare the control array in your code and initialize it in the form constructor. Like this:

避免使用建议的迭代方法,除非您的表单非常简单,否则您将获得相当随机的控件集合。只需在代码中声明控件数组并在表单构造函数中对其进行初始化。像这样:

Public Class Form1
    Private OrderNumbers() As TextBox

    Public Sub New()
        InitializeComponent()
        OrderNumbers = New TextBox() {TextBox1, TextBox2}
    End Sub
End Class

You can now treat OrderNumbers just like you could in VB6.

您现在可以像在 VB6 中一样处理 OrderNumbers。

回答by hafiz

Maybe this is simpler. To create a control array, I put the control array declaration in a module. For example, if I have a Form with three TextBoxes and I want the TextBoxes to be part of a control array called 'mytext', I declare my control array in a module as follows:

也许这更简单。为了创建一个控件数组,我将控件数组声明放在一个模块中。例如,如果我有一个包含三个 TextBox 的 Form 并且我希望 TextBoxes 成为名为“mytext”的控件数组的一部分,我将在一个模块中声明我的控件数组,如下所示:

Module Module1

Public mytext() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3}

End Module

And, I use the TextBoxes from the control array as follows:

而且,我使用控件数组中的 TextBoxes 如下:

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    mytext(0).Text = "Hello"
    mytext(1).Text = "Hi"
    mytext(2).Text = "There"

End Sub

End Class

You can even loop through the control array, like you could in VB6:

您甚至可以像在 VB6 中一样遍历控件数组:

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    For i As Integer = 0 To 2
        mytext(i).Text = i + 1
    Next

End Sub

End Class

The beauty of using a module is that the TextBoxes do not even need to be in the same form.

使用模块的美妙之处在于 TextBox 甚至不需要采用相同的形式。

回答by Steve Massing

So this is one of the features that did not make the transition to VB.NET -- exactly :-( However, you can accomplish much of what you would have done in VB6 with two different mechanisms in .NET: Looping through the controls collection and handling control events.

所以这是没有过渡到 VB.NET 的功能之一——正是 :-( 但是,您可以使用 .NET 中的两种不同机制完成您在 VB6 中所做的大部分工作:循环遍历控件集合和处理控制事件。

Looping Through the Controls Collection
In VB.NET every form and control container has a controls collection. This is a collection that you can loop through and then do an operation on the control like set the value.

循环遍历控件集合
在 VB.NET 中,每个窗体和控件容器都有一个控件集合。这是一个集合,您可以循环遍历,然后对控件执行操作,例如设置值。

Dim myTxt As TextBox
For Each ctl As Control In Me.Controls
  If TypeOf ctl Is TextBox Then
    myTxt = CType(ctl, TextBox)
    myTxt.Text = "something"
  End If
Next

In this code sample you iterate over the controls collection testing the type of the returned object. If you find a textbox, cast it to a textbox and then do something with it.

在此代码示例中,您遍历控件集合以测试返回对象的类型。如果你找到一个文本框,把它投射到一个文本框,然后用它做一些事情。

Handling Control Events
You can also handle events over multiple controls with one event handler like you would have using the control array in VB6. To do this you will use the Handles keyword.

处理控件事件
您还可以使用一个事件处理程序处理多个控件上的事件,就像在 VB6 中使用控件数组一样。为此,您将使用 Handles 关键字。

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged
  Dim myTxt As TextBox = CType(sender, TextBox)
  MessageBox.Show(myTxt.Text)
End Sub

The key here is the Handleskeyword on the end of the event handler. You separate out the various controls that you want to handle and the event by using a comma. Make sure that you are handling controls that have the same event declaration. If you ever wondered what senderwas for on every event well here's one of the uses for it. Cast the sender argument to the type of control that you are working with and assign it to a local variable. You will then be able to access and manipulate the control that fired the event just like you would have in VB6 if you specified and index to the array.

这里的关键是事件处理程序末尾的Handles关键字。使用逗号分隔要处理的各种控件和事件。确保您正在处理具有相同事件声明的控件。如果您想知道发送方在每个事件中的用途,这里是它的用途之一。将 sender 参数转换为您正在使用的控件类型并将其分配给局部变量。然后,您将能够访问和操作触发事件的控件,就像在 VB6 中一样,如果您指定并索引数组。

Using these two techniques you can replicate the functionality of control arrays in VB6. Good luck.

使用这两种技术,您可以在 VB6 中复制控件数组的功能。祝你好运。

回答by Daniel A. White

With Winforms, you could do this:

使用 Winforms,你可以这样做:

myForm.Controls _
  .OfType(Of TextBox) _
  .OrderBy(Function(c) c.Name) _
  .Where(Function(c) c.Name.StartsWith("somePrefix")) _
  .ToArray()

On your form you would name your textboxes somePrefix1, somePrefix2, etc.

在您的表单,您可以命名您的文本框somePrefix1somePrefix2等等。

Here is an oldarticlebut it could give you more information. The top method is super easy.

这是一篇文章,但它可以为您提供更多信息。上面的方法超级简单。

回答by msarchet

Your Form, or PanelControl, or anything else that can contain child controls will have a Property called Controls.

您的 Form、PanelControl 或任何其他可以包含子控件的东西都将有一个名为 的属性Controls

You can loop through all of the text boxes in a control by using

您可以使用以下命令遍历控件中的所有文本框

'Create a List of TextBoxes, like an Array but better Dim myTextBoxControls As New List

'创建一个文本框列表,就像一个数组,但更好地将 myTextBoxControls 调暗为新列表

For Each uxControl As UserControl in MyFormName.Controls
    If TypeOf(uControl) is TextBox
        myTextBoxControls.Add(uControl)
    End IF
Next

Now you have your iterate-able collection you can work with.

现在您有了可以使用的可迭代集合。

You can access a TextBoxes value with the EditValueproperty.

您可以使用该EditValue属性访问 TextBoxes 值。

After looking at what you're trying to do a little further.

在查看您想要进一步做的事情之后。

You probably want to name all of your controls with a Prefix, let's say abcfor now.

你可能想用前缀来命名你的所有控件,让我们abc现在说。

For Each uxControl As UserControl in MyFormName.Controls
    If TypeOf(uControl) is TextBox Then
        Dim tbControl As TextBox = DirectCast(uControl, TextBox)
        If tbControl.Name.StartsWith("abc") Then
            tbControl.EditValue = "the Value you want to initialize"
        End If
    End If
Next

回答by dbasnett

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click

    Dim a() As Control = GetControls("textbox")

    For Each c As TextBox In a
        c.Text = c.Name
    Next

End Sub

Private Function GetControls(typeOfControl As String) As Control()

    Dim allControls As New List(Of Control)
    'this loop will get all the controls on the form
    'no matter what the level of container nesting
    'thanks to jmcilhinney at vbforums
    Dim ctl As Control = Me.GetNextControl(Me, True)
    Do Until ctl Is Nothing
        allControls.Add(ctl)
        ctl = Me.GetNextControl(ctl, True)
    Loop
    'now return the controls you want
    Return allControls.OrderBy(Function(c) c.Name). _
        Where( _
            Function(c) (c.GetType.ToString.ToLower.Contains(typeOfControl.ToLower) AndAlso _
                         c.Name.Contains("Box")) _
                ).ToArray()
End Function