Why I can´t create a Linkbutton inside instantiatein method?

Posted on 2010-09-21
Last Modified: 2012-05-10
Why is not possible to create a linkbutton controll inside the instantiate method in a custom class and handle it from Item_DataBinding ?

The idea es to relate the onclick event with each element of the datalist.

Thanks in advance.
<%@ Page Language="VB" MasterPageFile="menu_principal.master" Title="Untitled Page" %>

<%@ MasterType VirtualPath="menu_principal.master" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="system.Data.OleDb" %>

<%@ Import Namespace="System.Collections.Generic" %>

<script runat="server">

    Protected Sub lnkDescargar_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Response.ContentType = "application/pdf"

        Response.AppendHeader("Content-Disposition", "attachment; filename=catalogo_de_premios_apsara.pdf")




    End Sub

    Public Class CustomTemplate

        Implements System.Web.UI.ITemplate

        Dim templateType As ListItemType

        Sub New(ByVal type As ListItemType)

            templateType = type

        End Sub


        Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) _

          Implements System.Web.UI.ITemplate.InstantiateIn

            Dim ph As New PlaceHolder()


            Select Case (templateType)

                Case ListItemType.Item

                    ph.Controls.Add(New LiteralControl( _

                      "<table runat=""server"" width=""270"" border=""0"" cellspacing=""0"" cellpadding=""0"">" & _

                      "<tr><td height=""150"" align=""center"" valign=""middle"" bgcolor=""#CCCCCC""><img src=""imagenes/3.png"" width=""270"" height=""120"" /></td>" & _

                      "</tr>" & _

                      "<tr>" & _

                        "<td height=""80"" align=""center"" valign=""top"" bgcolor=""909090"">" & _

                        "<table width=""270"" border=""0"" cellspacing=""0"" cellpadding=""0"" bgcolor=""#909090"">" & _

                          "<tr>" & _

                            "<td width=""15"" height=""30"">&nbsp;</td>" & _

                            "<td height=""30"" align=""right"" valign=""middle"" class=""inicio""><a href=""#"" class=""ficha""> Ver Galería</a></td>" & _

                            "<td width=""18"" height=""30"">&nbsp;</td>" & _

                          "</tr>" & _

                          "<tr>" & _

                            "<td width=""15"" height=""50"">&nbsp;</td>" & _

                            "<td align=""right"" valign=""top"" class=""categorias"">" & _

                              "<table width=""100%"" border=""0"" height=""170"">" & _



                    For i As Short = 1 To 15

                        Dim fila = New TableRow

                        Dim celdacampo As New TableCell

                        Dim celdainter = New TableCell

                        Dim celdavalor As New TableCell

                        fila.ID = "fila" & i.ToString

                        celdacampo.ID = "CAMPO" & i.ToString

                        celdacampo.Width = "30"

                        celdacampo.CssClass = "categorias"

                        celdainter.Width = "13"

                        celdainter.Text = "&nbsp;"

                        celdavalor.ID = "VALOR" & i.ToString

                        celdavalor.CssClass = "info"






                    ph.Controls.Add(New LiteralControl( _

                                            "</table>" & _

                                                  "<br /></td>" & _

                                                "<td width=""18"">&nbsp;</td>" & _

                                              "</tr>" & _

                                              "<tr>" & _

                                                "<td height=""10"">&nbsp;</td>" & _

                                                "<td height=""30"" align=""right"" valign=""middle"" class=""info"">"))

                    Dim lnkbutton As New LinkButton

                    lnkbutton.ID = "lbtnArchivo"

                    lnkbutton.Text = "Descarga Ficha Técnica Aquí"



                    ph.Controls.Add(New LiteralControl( _

                                                "</td>" & _

                                                "<td>&nbsp;</td>" & _

                                              "</tr>" & _

                                            "</table>" & _

                                            "</td>" & _

                                          "</tr>" & _



                    AddHandler ph.DataBinding, New EventHandler(AddressOf Item_DataBinding)

            End Select


        End Sub

    End Class


    Shared Sub Item_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim ph As PlaceHolder = CType(sender, PlaceHolder)

        Dim ri As DataListItem = CType(ph.NamingContainer, DataListItem)

        For i As Integer = 1 To 15

            Dim fila As TableRow = CType(ph.FindControl("fila" & i.ToString), TableRow)

            Dim titulocampo As String = "CAMPO" & i.ToString

            Dim titulovalor As String = "VALOR" & i.ToString

            Dim enlace As LinkButton = CType(FindControl("lbtnArchivo"), LinkButton)

            Dim campo As String = Convert.ToString(DataBinder.Eval(ri.DataItem, titulocampo))

            Dim valor As String = Convert.ToString(DataBinder.Eval(ri.DataItem, titulovalor))

            If String.IsNullOrEmpty(valor) Then

                fila.Visible = False


                CType(ph.FindControl(titulocampo), TableCell).Text = campo

                CType(ph.FindControl(titulovalor), TableCell).Text = valor

            End If


    End Sub

    Protected Sub Page_Load(ByVal sender As Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        Dim GetIdCategoria As Int32

        If Not IsPostBack Then

            If Request.QueryString.Count > 0 Then

                If Not IsNothing(Request.QueryString("idcategoria")) Then

                    GetIdCategoria = Request.QueryString("idcategoria")

                End If


                ' Si los valores obtenidos por GET no existen evalua los controles locales

                If Not String.IsNullOrEmpty(Master.mddlCategorias.SelectedValue.ToString) Then

                    GetIdCategoria = CType(Master.mddlCategorias.SelectedValue, Int32)


                    GetIdCategoria = 1 'Categoria default para TODAS

                End If

            End If


            ' Si los valores obtenidos por GET no existen evalua los controles locales

            If Not String.IsNullOrEmpty(Master.mddlCategorias.SelectedValue.ToString) Then

                GetIdCategoria = CType(Master.mddlCategorias.SelectedValue, Int32)


                GetIdCategoria = 1 'Categoria default para TODAS

            End If

        End If



        Dim conn As OleDbConnection ' Archivo

        Dim ComandoLectura As OleDbDataAdapter ' SQL

        Dim LineaSQL As String


        'Establecer conexion

        conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|qcontroll.mdb;")

        'LineaSQL = "SELECT Secciones.SECCION, Categorias.CATEGORIA, ProductosNuevosCampos.CAMPO1, ProductosNuevos.VALOR1, " & _

        '           "ProductosNuevosCampos.CAMPO2, ProductosNuevos.VALOR2, ProductosNuevosCampos.CAMPO3, ProductosNuevos.VALOR3, " & _

        '           "ProductosNuevosCampos.CAMPO4, ProductosNuevos.VALOR4, ProductosNuevosCampos.CAMPO5, ProductosNuevos.VALOR5, " & _

        '           "ProductosNuevosCampos.CAMPO6, ProductosNuevos.VALOR6, ProductosNuevosCampos.CAMPO7, ProductosNuevos.VALOR7, " & _

        '           "ProductosNuevosCampos.CAMPO8, ProductosNuevos.VALOR8, ProductosNuevosCampos.CAMPO9, ProductosNuevos.VALOR9, " & _

        '           "ProductosNuevosCampos.CAMPO10, ProductosNuevos.VALOR10, ProductosNuevosCampos.CAMPO11, ProductosNuevos.VALOR11, " & _

        '           "ProductosNuevosCampos.CAMPO12, ProductosNuevos.VALOR12, ProductosNuevosCampos.CAMPO13, ProductosNuevos.VALOR13, " & _

        '           "ProductosNuevosCampos.CAMPO14, ProductosNuevos.VALOR14, ProductosNuevosCampos.CAMPO15, ProductosNuevos.VALOR15 " & _

        '           "FROM (Secciones INNER JOIN (Categorias INNER JOIN ProductosNuevos ON Categorias.ID_CATEGORIA = ProductosNuevos.ID_CATEGORIA) " & _

        '           "ON Secciones.ID_SECCION = ProductosNuevos.ID_SECCION) INNER JOIN ProductosNuevosCampos ON Secciones.ID_SECCION = ProductosNuevosCampos.ID_SECCION"


        LineaSQL = "SELECT Secciones.SECCION, Categorias.CATEGORIA, ProductosUsados.PRECIO, ProductosUsados.MONEDA, ProductosUsados.IVA, " & _

                       "ProductosUsadosCampos.CAMPO1, ProductosUsados.VALOR1, ProductosUsadosCampos.CAMPO2, ProductosUsados.VALOR2, " & _

                       "ProductosUsadosCampos.CAMPO3, ProductosUsados.VALOR3, ProductosUsadosCampos.CAMPO4, ProductosUsados.VALOR4, " & _

                       "ProductosUsadosCampos.CAMPO5, ProductosUsados.VALOR5, ProductosUsadosCampos.CAMPO6, ProductosUsados.VALOR6, " & _

                       "ProductosUsadosCampos.CAMPO7, ProductosUsados.VALOR7, ProductosUsadosCampos.CAMPO8, ProductosUsados.VALOR8, " & _

                       "ProductosUsadosCampos.CAMPO9, ProductosUsados.VALOR9, ProductosUsadosCampos.CAMPO10, ProductosUsados.VALOR10, " & _

                       "ProductosUsadosCampos.CAMPO11, ProductosUsados.VALOR11, ProductosUsadosCampos.CAMPO12, ProductosUsados.VALOR12, " & _

                       "ProductosUsadosCampos.CAMPO13, ProductosUsados.VALOR13, ProductosUsadosCampos.CAMPO14, ProductosUsados.VALOR14, " & _

                       "ProductosUsadosCampos.CAMPO15, ProductosUsados.VALOR15 " & _

                       "FROM (Secciones INNER JOIN (Categorias INNER JOIN ProductosUsados ON Categorias.ID_CATEGORIA = ProductosUsados.ID_CATEGORIA) " & _

                       "ON Secciones.ID_SECCION = ProductosUsados.ID_SECCION) INNER JOIN ProductosUsadosCampos ON Secciones.ID_SECCION = ProductosUsadosCampos.ID_SECCION "

        If GetIdCategoria > 1 Then LineaSQL = LineaSQL & "WHERE (((ProductosUsadosCampos.ID_SECCION)=" & GetIdCategoria.ToString & "))"


        ComandoLectura = New OleDbDataAdapter(LineaSQL, conn)

        Dim Tabla As DataTable = New DataTable

        'dlProductos.HeaderTemplate = New CustomTemplate(ListItemType.Header)

        dlProductos.ItemTemplate = New CustomTemplate(ListItemType.Item)

        'dlProductos.AlternatingItemTemplate = New CustomTemplate(ListItemType.AlternatingItem)

        'dlProductos.FooterTemplate = New CustomTemplate(ListItemType.Footer)


        'Ordenar la estructura de datos

        dlProductos.DataSource = Tabla


    End Sub


<asp:Content ID="Content1" ContentPlaceHolderID="cphProductos" Runat="Server">

        <asp:datalist ID="dlProductos" runat="server" CellPadding="0" CellSpacing="12"

                      RepeatColumns="3" RepeatDirection="Horizontal" BorderWidth="0px" 

                      HorizontalAlign="Left" ShowFooter="False" ShowHeader="False" >



Open in new window

Question by:dimensionav
  • 4

Author Comment

ID: 33729429
I got problems with this line, inside Item_DataBinding event::

            Dim enlace As LinkButton = CType(FindControl("lbtnArchivo"), LinkButton)

Author Comment

ID: 33730134
I would like to give a better perspective of this problem:

I am trying to enable a download link per each item in the datalist, each link must be associated to a different and unique file, so if you think there would be a better way to do this, please letme know
LVL 26

Accepted Solution

Alan Warren earned 500 total points
ID: 33753238
Hi dimensionav,
if you are populating your datalist from a stored procedure or some sql, you could populate a field to be used as the download link, a NavigateUrl, perhaps an asp:hyperlink control could be used instead of a linkbutton. No .net code involved, just some SQL.

                  Text='<%# Eval("The_Download_Link_Hyperlink_Text") %>'
                  NavigateUrl='<%# Eval("The_Download_Link_Hyperlink_NavigateUrl") %>'




Author Comment

ID: 33758827
The main problem is that the itemtemplate is created before to be databinded, so after that I have to find each control and bind it to its corresponding data

Author Closing Comment

ID: 33855567
I have performed some changes to my code and it used yours


Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (…
Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now