Code to add a control (and its handler) to a Placeholder

I can think of several ways to add a variable number of controls to a web page... repeaters, grids, etc. 

Today I'm looking at a much simpler approach. I'm going to drop a Placeholder control on a web page, and run code that puts a dynamic number of link buttons in the placeholder. 

Related Articles

... and you 'll find more on the NET Development Menu

On the front side:

<asp:PlaceHolder runat="server" ID="placeholder1"></asp:PlaceHolder>

Code behind:

!! This goes in the page load, outside of the 'if not postback'

'populate a datatable with all of the 'quote ids' that we'll create a linkbutton for
Dim oDT As DataTable
oDT = SPs.fp_FPTakeoffQuote_SEL_byMasterID(mFPTakeoff3.intMasterNumber, App.ConnectionString).getTable
 
'loop through the datatable
For Each oRow In oDT.Rows
    'create a new link button
    Dim lnk As New LinkButton
    'set its properties
    lnk.Text = String.Format("Quote {0}", oRow("TakeoffQuoteID"))
    lnk.CommandArgument = oRow("TakeoffQuoteID")
    'add a handler for the click event
    AddHandler lnk.Click, AddressOf LinkHandler
    'add the control to the placeholder
    placeholder1.Controls.Add(lnk)
 
    'add a 'space', so the links don't touch each other
    Dim lit As New Literal
    lit.Text = " "
    placeholder1.Controls.Add(lit)
Next

 

 

 

Sub LinkHandler(sender As Object, e As EventArgs)
    Dim strError As String = ""
    Try
        Dim lnk As LinkButton = CType(sender, LinkButton)
 
        Session("TakeoffQuoteID") = lnk.CommandArgument
        Response.Redirect(String.Format("ViewQuote.aspx?Path={0}", Session("Path")))
 
 
    Catch ex As ThreadAbortException
    Catch ex As Exception
        ErrorHandler.globalErrorHandler(ex, strError, App.AppName, App.UserName, False)
        Me.lblError.Text = ex.Message
 
    End Try
 
End Sub

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences