如何在运行时重命名标签名称是可能的吗?在vb.net中



我使用了标签1到标签75,是否可以更改标签名称?示例:我想将标签名称重命名为label3,而不是label7。解决方案是什么?

它在表单中有效,因为您正在调用Controls,这意味着Me.Controls,它是Me(您的表单)内部的控件集合。将标签放入面板后,标签将不再位于窗体的控件集合中,而是面板的控件集合。这是因为Controls不会比它调用的控件更深。你可以这样做,这将解决你的直接问题:

' replace Panel1 with the name of your panel
Dim lbl As Label = Panel1.Controls("Label" & Data)
ReceivedFrame = ReceivedFrame + 1
lbl.Text = ReceivedFrame

但是,如果标签从面板中移出,就会断开。下面的解决方案在处理能力方面有些昂贵,但我在任何地方都使用它,这不是一个问题。

在你的项目中创建一个新的类文件,并将这些代码放入其中

Public Module Support
    <Extension()> _
    Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
        Dim result As New List(Of Control)
        For Each ctrl As Control In parent.Controls
            If TypeOf ctrl Is T Then result.Add(ctrl)
            result.AddRange(ctrl.ChildControls(Of T)())
        Next
        Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
    End Function
    <Extension()> _
    Public Function ControlByName(ByVal parent As Control, ByVal name As String) As Control
        For Each c As Control In parent.ChildControls
            If c.Name = name Then
                Return c
            End If
        Next
        Return Nothing
    End Function
End Module

它使您能够获取包含窗体的控件中的所有控件。然后按名称获取所需控件。

然后你可以这样称呼它:

Dim lbl As Label = Me.ControlByName("Label" & Data)
ReceivedFrame = ReceivedFrame + 1
lbl.Text = ReceivedFrame

只要控件位于表单中的某个位置,在任何容器中,或者在另一个容器中的任何容器中就可以了。

Dim lbl As New Label
lbl.Parent = Panel1
lbl.Text = "Your string"

您可以直接通过Label控件的Name属性调用它,无论它位于窗体上。如果Label控件位于面板上,并且它的名称为Label1,则要显示一个值,您可以通过编程将其调用为Label1.Text="Your String value"

如果您想通过对象访问标签控件的属性,则

Dim lbl As Label = CType(Label1, Label)
lbl.Text ="Your String Value"

HTH

这是他在@Verdolino编写的一个很好的代码,但有点bug,因为如果你的控件嵌套在一个嵌套的组框中,而这个组框仍然嵌套在其他控件中,它就会崩溃。

但这是一个很好的方法。这是一个递归函数,它将查看嵌套控件。

Function GetControl(OwnerControl as Control,FindControlName as string) as Control
     If OwnerControl.Controls.Count > 0 Then
        '//===>It will loop in each control of the control container.
        For Each iControl as Control in OwnerControl.Control
             GetControl(OwnerControl ,FindControlName)
        Next
     Else
         '//===>this code is when the control is not a container and will check if the name macth
         If OwnerControl.Name.ToUpper =  FindControlName.ToUpper Then
               '//===>TODO HERE:Add here any code if the control was found
               ' you can register some events handler if you want
               ' AddHandler OwnerControl.Click, AddressOf _MyClickEventSub
                Return OwnerControl
         End If
     End If
End Sub
dim txtControl as control = GetControl(Me,"txtName")
If not txtControl Is Nothing Then
  '//===>TODO HERE:if the control was found
End Sub

最新更新