indirect name referencing in vb.net

Aquitus 146 Reputation points
2022-02-13T04:37:46.667+00:00

my code goes like
for each c as control in controls
if c.name = "chklst" + counter then
c.items.add(newitem)
end if
next
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?

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

Accepted answer
  1. LesHay 7,136 Reputation points
    2022-02-13T09:19:52.743+00:00

    Hi

    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"
        Controls.Add(chklst)
    
        ' 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
        Next
    
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 118.5K Reputation points
    2022-02-13T09:08:28.88+00:00

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

    Dim lb = CType(c, CheckedListBox)
    lb.Items.Add(newitem)
    

    Or show more details about "doesnt work".

    1 person found this answer helpful.

  2. Sreeju Nair 12,456 Reputation points
    2022-02-13T05:38:04.977+00:00

    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:

    https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.findcontrol?view=netframework-4.8

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.