Jamie Hartnoll
Jamie Hartnoll

Reputation: 7341

Dynamically Adding Multiple User Controls vb.net

I have a User Control which returns a table of data, which in some cases needs to be looped, displaying one on top of another.

I am able to dynamically add a single instance of this by placing a fixed placeholder in the page.

I am now trying to work out how to add more than one, given that I don't know how many might be needed I don't want to hard code the Placeholders.

I've tried the following, but I am just getting one instance, presumably the first is being overwritten by the second

My HTML

<div id="showHere" runt="server"/>

VB

Dim thisPh As New PlaceHolder
thisPh.Controls.Add(showTable)
showHere.Controls.Add(thisPh)

Dim anotherPh As New PlaceHolder
anotherPh .Controls.Add(showTable)
showHere.Controls.Add(anotherPh)

How do I make it add repeated tables within the showHere div?

Upvotes: 1

Views: 6378

Answers (3)

ferricguy
ferricguy

Reputation: 1

After fussing with this issue myself, I stumbled across below solution.

On button click()

    LocationDiv.Visible = True
    Dim existingItems As New List(Of Object)

    If Not Session("existingItems") Is Nothing Then
        existingItems = CType(Session("existingItems"), List(Of Object))

        For Each item As Object In existingItems
            LocationDiv.Controls.Add(item)
        Next
        existingItems.Clear()
    End If

    LocationDiv.Controls.Add(New LiteralControl("<b>" & Text & "</b>"))

    For Each item As Object In LocationDiv.Controls
        existingItems.Add(item)
    Next

    Session.Add("existingItems", existingItems)

Upvotes: 0

VinayC
VinayC

Reputation: 49215

I would advise generating a different ID for each of your table. For example,

Dim i As Integer
i = 0
For each tbl in ShowTables
    tbl.ID = "MyTab" + i.ToString()
    i = i + 1
    showHere.Controls.Add(tbl)
    showHere.Controls.Add(New LiteralControl("<br />"))
Next

On other hand, it would make more sense to have a your user/custom control generate html for a single table and then nest your user/custom control within a repeater (or similar control such as ListView etc).

Upvotes: 1

Amen Ayach
Amen Ayach

Reputation: 4348

Did you tried simply, this:

For each tbl in ShowTables        
    showHere.Controls.Add(tbl)
    showHere.Controls.Add(New LiteralControl("<br />"))
Next

Upvotes: 1

Related Questions