Background Color:
Background Pattern:
Sunday, August 20, 2017
menu click

Find a label by name in a form.controls collection and change its text value.

You don't need 20 if...then statements

Author: Ibrahim/Monday, August 19, 2013/Categories: Code Blog, VB Solutions

Rate this article:
No rating

Okay, so I am cherry picking questions on the MSDN forums and answering them.  Its a way to add articles to this web site (new at the time of writing this) and provide some solutions for beginning programmers.


This problem was from someone who had to change the value of a label's text based on a callback from a Weather API.  The callback provided an index to the value changed and the code had to select a label using that index and then change the label's text property using the API's supplied indexed value.


The Problem:

The form had 20 labels named Label1 through Label20.  The API would provide an Index from 0 to 19 that indicated what value changed.  The original code actually had 20 If...Then statements that checked for a matching index then modified the right label accordingly.

At first glance you would say that this should have used a Select...Case instead.  But that was still wasteful code IMHO, though some might point out that the Select...Case statement was inline code that had to run faster than anything with a loop of Linq Query.

True, but this situation was not in a iterative loop where processor cycles can become critical. So I opted for cleaner and more compact code.

Here is the solution:



  Private LabelList As List(Of Label)

    ''' Call this in form constructor
    Private Sub SetLabelList()

        LabelList = New List(Of Label)

        For Each Item As Control In Me.Controls
            If TypeOf (Item) Is Label Then
            End If

    End Sub

    ''' Call this passing index of item
    Private Sub UpdateLabel(Index As Integer)

        Dim Result As Label

        Result = (From LB In LabelList Where LB.Name.Equals("Label" & Index + 1)).FirstOrDefault

        If Result IsNot Nothing Then
            Result.Text = fdInfo.DFD(Index).Title
        End If

    End Sub

hello world

The solution requires that you import these libraries:


Imports System.Linq
Imports System.Collections.ObjectModel

In the forms constructor I call the SetLabelList() first to set up the list of labels. Then the UpdateLabel() method is called to update the label text passing the index provided by the API.

That's it.  Yeah  I know.  Not rocket science, but for junior programmers the most efficient solutions are not always so obvious.

Number of views (2104)/Comments (0)


Please login or register to post comments.