PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
Multiple labels-VBForums
Results 1 to 12 of 12

Thread: Multiple labels

  1. #1

    Thread Starter
    Member
    Join Date
    Jan 2015
    Posts
    37

    Multiple labels

    I want to create 20 labels and handel them individually. This would have been simple in VB6 with an array of labels, but in VB.Net it has to be done in runtime. By adapting something I found on line I managed this which works fine up to a point:

    Dim i = 0
    For i = 1 To 20
    Dim label As New Label()
    label.Location = New Point(10, 25 * i)
    label.Size = New Size(1000, 20)
    label.Name = "label_" & i
    label.Text = "This is label " & i
    Panel2.Controls.Add(label)
    Next

    However there are two problems:

    1 It won't let me set the font size (read only). It's set at 8.25
    2 It doesn't allow me to use the names I have given the labels. e.g. Label_1.BackColor = Color.MistyRose (Label1 not declared)

    Is there any way round these?

  2. #2
    Frenzied Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    1,435

    Re: Multiple labels

    Hi,

    not sure about the Fontsize, but everything else you can do..

    Code:
    Option Strict On
    
    Public Class Form5
    
        Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim i As Integer
            For i = 1 To 20
    
                Dim Lbl As New Label
                AddHandler Lbl.Click, AddressOf Clickme
                Lbl.Location = New Point(10, 25 * i)
                Lbl.Size = New Size(1000, 20)
                Lbl.Text = CStr(i)
                Lbl.Visible = True
                Lbl.Text = "This is label " & i
                Lbl.Tag = "Label " & i
                Lbl.BackColor = Color.MistyRose
                FlowLayoutPanel1.Controls.Add(Lbl)
            Next
        End Sub
    
        Private Sub Clickme(ByVal sender As Object, ByVal e As EventArgs)
            Dim Lbl As Label
            Lbl = CType(sender, Label)
            Dim str As String = CStr(Lbl.Tag)
            MessageBox.Show(str)
        End Sub
    End Class
    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  3. #3
    Fanatic Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    925

    Re: Multiple labels

    Code:
            Dim i = 0
            For i = 1 To 20
                Dim label As New Label()
                label.Location = New Point(10, 25 * i)
                label.Size = New Size(100, 20)
                label.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                label.Name = "label_" & i
                label.Text = "This is label " & i
                Panel2.Controls.Add(label)
            Next
    
            Panel2.Controls("label_1").BackColor = Color.MistyRose

  4. #4
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,216

    Re: Multiple labels

    vb Code:
    1. Public Class Form1
    2.  
    3.  
    4.     Private ReadOnly _mLabels As New List(Of Label)(Enumerable.Range(1, 20).Select(Function(n) CreateLabel(n)))
    5.  
    6.  
    7.     Private Sub Generate()
    8.         For Each lb In me._mlabels
    9.             AddHandler lb. ' ... Event/method address
    10.         Next
    11.  
    12.  
    13.         ' Add controls.....
    14.     End Sub
    15.  
    16.  
    17.     Private Shared Function CreateLabel(point As Integer) As Label
    18.         Return New Label With
    19.             {
    20.                 .Location = New Point(10, 25 * point),
    21.                 .Size = New Size(1000, 20),
    22.                 .Name = $"label_{point}",
    23.                 .Text = $"This is label {point}"
    24.             }
    25.     End Function
    26. End Class

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,756

    Re: Multiple labels

    As TopShot noted, while Font SIZE is readonly, that's only because it's just an aspect of the Font, which is what you are really setting.

    In VB6 you made control arrays. This was a means for allowing multiple controls to all share an event handler. People often used them for making collections of controls, but you can do that in either language. There isn't the same need for the control array in .NET, because the Handles clause is how you hook event handlers to controls, and you can chain Handles clauses together if you want one event handler to handle events from multiple controls. However, that leaves out the ease of creating collections of controls. That's not so difficult in .NET, either, it just isn't as easy as it was in VB6.

    Note that every control ends up in a Controls collection. You are adding the label to a controls collection, so you are already aware of that, though you may not have recognized the significance. Essentially, it means that all your controls are already in a collection. They may be stuffed in with a bunch of other controls, too, but you have one place to look for them. So, if you add all the labels in the designer, they all end up in a Controls collection. As long as they all end up in the SAME controls collection (there aren't some on a panel, some on the form, and others in a groupbox), then you could get them into your own list(of Label) with a single line of code. Sure, that single line is more than you had to do in VB6, but not much more, and the control array in VB6 wasn't really about collections of controls anyways.
    My usual boring signature: Nothing

  6. #6

    Thread Starter
    Member
    Join Date
    Jan 2015
    Posts
    37

    Re: Multiple labels

    Brilliant! I'm not pretending to understand it all but it works fine. Thanks

  7. #7
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,658

    Re: Multiple labels

    Quote Originally Posted by PaMarn View Post
    I want to create 20 labels and handel them individually. This would have been simple in VB6 with an array of labels, but in VB.Net it has to be done in runtime....
    2 It doesn't allow me to use the names I have given the labels. e.g. Label_1.BackColor = Color.MistyRose (Label1 not declared)
    ...
    I usually wouldn't want to use the names given the labels anyway, I would want to use an Index like you would have used in VB6, so would add the labels to an array or list as Shaggy Hiker mentioned.
    Code:
      Private labels() As Label
    
      Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        labels = {Label1, Label2, Label3, Label4, Label5, Label6, Label7, Label8, Label9, Label10}
    
        For i As Integer = 0 To UBound(labels)
          If (i And 1) = 1 Then
            labels(i).BackColor = Color.Red
          End If
        Next
      End Sub
    The above loop should address the labels with even names, i.e. indexes 0=Label1, 1=Label2, 2=label3, etc..., and set their backcolor to Red.

    If you wanted to share an event, you could also select all the labels in the IDE that you wanted to share an event, then double click on the event in the properties window (event option chosen) and the declaration of the event handler, with all the control events added to the handles clause for you.
    You would then normally just cast the sender argument to a label type to access all the properties of the label which triggered the event.

  8. #8

    Thread Starter
    Member
    Join Date
    Jan 2015
    Posts
    37

    Re: Multiple labels

    I thought I had cracked it with this code as it didn't throw up any errors :

    Dim TextLabel() As Label = New Label() {}

    Dim i = 0
    For i = 0 To 20
    TextLabel(i).Location = New Point(10, 25 * i)
    TextLabel(i).Size = New Size(500, 20)
    TextLabel(i).Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.GraphicsUnit.Point)
    TextLabel(i).Name = "label_" & i + 1
    TextLabel(i).Text = "This is label " & i + 1
    Panel3.Controls.Add(TextLabel(i))
    Next

    Panel3.Controls("TextLabel(2)").BackColor = Color.MistyRose

    But the labels don't show. Is something missing?

  9. #9
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,216

    Re: Multiple labels

    Turn option strict on. I gave you a nice example above. You never add any labels to TextLabel().

  10. #10

    Thread Starter
    Member
    Join Date
    Jan 2015
    Posts
    37

    Re: Multiple labels

    I'm sorry if I'm being thick here, or maybe I didn't explain well what I'm trying to do. You've given me examples of how to put design-time-created labels into an array, and how to to create labels at runtime so that I can select the font size. I need both of these - runtime-created labels in an array so that the user can use Next and Back buttons to highlight a label (and hear the text spoken).

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,756

    Re: Multiple labels

    Right, and Ident had the key tip: You are creating the collection here:

    Dim TextLabel() As Label = New Label() {}

    You then create a bunch of labels, but at no time do you ever put the labels into the collection.

    However, since you will be building this dynamically, you don't actually want an array of labels to start with. A list(of Label) would be better (and a Dictionary might also suit, but there isn't a clear reason, yet). So, what you want is more like this:

    Dim textLabels As new List(of Label)

    Then your loop could look like this:
    Code:
    For i = 0 To 20
     Dim nl As New Label
     nl.Location = New Point(10, 25 * i)
     nl.Size = New Size(500, 20)
     nl.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.GraphicsUnit.Point)
     nl.Name = "label_" & i + 1
     nl.Text = "This is label " & i + 1
     Panel3.Controls.Add(nl)
     textLabels.Add(nl) 'This is where it gets added to your collection.
    Next
    If you really wanted it to be an array, you could always call .ToArray after the loop has filled the collection, but there's no reason to do that unless you had to pass the array to a method that required an array of labels. Leaving it as a list means that you don't have to worry about the size, so you could add more, or less, or add some later, or remove some, or whatever.
    My usual boring signature: Nothing

  12. #12
    Fanatic Member
    Join Date
    Sep 2017
    Posts
    687

    Re: Multiple labels

    I'd do somthing like this, or am I missing something?

    Code:
    Option Strict On
    Public Class FormCtrls
        Private Sub FormCtrls_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            For i = 0 To 20
                FlowLayoutPanel1.Controls.Add(New Label With
                                              {.Name = "Label" & i, .Text = "Label" & i,
                                               .Font = New Font("Arial", 10, FontStyle.Regular),
                                               .ForeColor = Color.MistyRose})
            Next
            For Each Ctrl As Control In FlowLayoutPanel1.Controls
                If TypeOf Ctrl Is Label Then
                    Dim Lab As Label = DirectCast(Ctrl, Label)
                    AddHandler Lab.Click, AddressOf DoSomething
                End If
            Next
        End Sub
    
        Private Sub DoSomething(Sender As Object, e As EventArgs)
            Dim Lab As Label = DirectCast(Sender, Label)
            MsgBox(Lab.Name) 'etc
        End Sub
    End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width