[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

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

Posted on 2010-09-21
5
Medium Priority
?
638 Views
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")
        Response.TransmitFile(Server.MapPath("~/DESCARGAS/catalogo_de_premios_apsara.pdf"))
        Response.End()
        MsgBox("click")
    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"">" & _
                                "<tr>"))
                    
                    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"
                        fila.Cells.Add(celdacampo)
                        fila.Cells.Add(celdainter)
                        fila.Cells.Add(celdavalor)
                        ph.Controls.Add(fila)
                    Next

                    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(lnkbutton)
                    
                    ph.Controls.Add(New LiteralControl( _
                                                "</td>" & _
                                                "<td>&nbsp;</td>" & _
                                              "</tr>" & _
                                            "</table>" & _
                                            "</td>" & _
                                          "</tr>" & _
                                        "</table>"))
                       
                    AddHandler ph.DataBinding, New EventHandler(AddressOf Item_DataBinding)
            End Select

            container.Controls.Add(ph)
        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
            Else
                CType(ph.FindControl(titulocampo), TableCell).Text = campo
                CType(ph.FindControl(titulovalor), TableCell).Text = valor
            End If
        Next

    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
            Else
                ' 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)
                Else
                    GetIdCategoria = 1 'Categoria default para TODAS
                End If
            End If
        Else
            ' 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)
            Else
                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)
        ComandoLectura.Fill(Tabla)

        'Ordenar la estructura de datos
        dlProductos.DataSource = Tabla
        dlProductos.DataBind()
    End Sub


    </script>

<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" >
        </asp:datalist>                    

</asp:Content>

Open in new window

0
Comment
Question by:dimensionav
  • 4
5 Comments
 

Author Comment

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

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

Author Comment

by:dimensionav
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
0
 
LVL 26

Accepted Solution

by:
Alan Warren earned 2000 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.

<asp:hyperlink
                  ID="TheDownloadLink_HyperLink"
                  runat="server"
                  Text='<%# Eval("The_Download_Link_Hyperlink_Text") %>'
                  NavigateUrl='<%# Eval("The_Download_Link_Hyperlink_NavigateUrl") %>'

...

hth

Alan
0
 

Author Comment

by:dimensionav
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
0
 

Author Closing Comment

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

Thanks!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
There may be issues when you are trying to access Outlook or send & receive emails or due to Outlook crash which leads to corrupt or damaged PST file. To eliminate the corruption from your PST file, you need to repair the corrupt Outlook PST file. U…

590 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