indirect name referencing in

Aquitus 146 Reputation points

my code goes like
for each c as control in controls
if = "chklst" + counter then
end if
the problem im having is "c.items.add(newitem)" doesnt work, if i replace "c" with the direct name it works but as it is it doesnt. how can i properly add an item in this case?
or perhaps theres a better way for me to indirectly reference the name?

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,555 questions
{count} votes

Accepted answer
  1. LesHay 7,126 Reputation points


    Here is a hacked up version that works. Hacked up because I had to invent some details for the example.

        ' in your case the listbox is already
        ' on the Form
        Dim chklst As New CheckedListBox
        chklst.Name = "chklst123"
        ' I have invented newitem value
        Dim newitem As String = "123456789"
        Dim counter As String = "123"
        For Each c As Control In Controls
          If c.Name = "chklst" + counter Then
            Dim cont As CheckedListBox = TryCast(c, CheckedListBox)
            If Not cont Is Nothing Then cont.Items.Add(newitem)
          End If
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 111.5K Reputation points

    Maybe you must cast c to the type of your control. For example, if it is CheckedListBox:

    Dim lb = CType(c, CheckedListBox)

    Or show more details about "doesnt work".

    1 person found this answer helpful.

  2. Sreeju Nair 11,601 Reputation points

    In C#, a foreach loop iterate over all the elements in a collection. During each pass through the loop, the loop variable is set to an element from the collection. But the loop variable is readonly, so any changes you apply will be discarded.

    So basically, if you want to add a control, you need to create a new variable that points to the control and then use add child controls. Refer:

    0 comments No comments