Compartir a través de


Enlazar datos SQL a un control Repeater

Repeater es un control de lista enlazado a datos cuya apariencia está totalmente controlada por sus plantillas. A diferencia de DataList, un control Repeater no procesa sus plantillas dentro de una tabla HTML y no incluye la posibilidad de seleccionar o editar.

En el siguiente ejemplo de código se muestra un control Repeater enlazado a un SqlDataReader que devuelve un conjunto de registros de datos de sólo avance y de sólo lectura devueltos por una consulta SQL, que contiene información acerca de un conjunto de libros. En este ejemplo se utiliza un SqlDataReader para incrementar el rendimiento. En el ejemplo también se define un elemento HeaderTemplate y un elemento FooterTemplate que se procesan al principio y al final de la lista, respectivamente.

El control Repeater realiza iteraciones por los datos enlazados, procesando el ItemTemplate una vez por cada elemento de la colección DataSource. Sólo procesa los elementos contenidos en sus plantillas.

Para ver la ejecución de un ejemplo similar (sin acceso a base de datos), hay que ejecutar el ejemplo Repeater1.aspx del Tutorial de ASP.NET.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
   <script language="VB" runat="server">
      Sub Page_Load(sender As Object, e As EventArgs) 
         '  Create a connection to the "pubs" SQL database located 
         ' on the local computer.
         Dim myConnection As SqlConnection 
         Dim myCommand As SqlDataAdapter
         ' Connect to the SQL database using a SQL SELECT query to get 
         ' all the data from the "Titles" table.
         myConnection = New SqlConnection("server=localhost;" _ 
            & "database=pubs;Trusted_Connection=Yes")
         myCommand = New SqlDataAdapter("SELECT * FROM Titles", _
            myConnection)
         ' Create and fill a  DataSet.
         Dim ds As Dataset = new DataSet()
         myCommand.Fill(ds)
         ' Bind MyRepeater to the  DataSet. MyRepeater is the ID of the
         ' Repeater control in the HTML section of the page.
         MyRepeater.DataSource = ds
         MyRepeater.DataBind()
      End SUb
   </script>

<body>
   <ASP:Repeater id="MyRepeater" runat="server">
      <HeaderTemplate>
         <Table width="100%" style="font: 8pt verdana">
            <tr style="background-color:DFA894">
               <th>
                  Title
               </th>
               <th>
                  Title ID
               </th>
               <th>
                  Type
               </th>
               <th>
                  Publisher ID
               </th>
               <th>
                  Price
               </th>
            </tr>
      </HeaderTemplate>
      <ItemTemplate>
            <tr style="background-color:FFECD8">
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "title") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "title_id") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "type") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "pub_id") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "price", _
                     "{0:c}") %>
               </td>
            </tr>
      </ItemTemplate>
      <FooterTemplate>
         </table>

      </FooterTemplate>
   </ASP:Repeater>
</body>
</html>

[C#]
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
   void Page_Load(Object sender, EventArgs e) 
   {
      //  Create a connection to the "pubs" database located 
      // on the local computer.
      SqlConnection myConnection = new SqlConnection("server=localhost;" +
         "database=pubs;Trusted_Connection=Yes");
      // Connect to the SQL database using a SQL SELECT query to get 
      // all the data from the "Titles" table.
      SqlDataAdapter myCommand = new SqlDataAdapter("SELECT * FROM" +
         " Titles", myConnection);
      // Create and fill a DataSet.
      DataSet ds = new DataSet();
      myCommand.Fill(ds);
      // Bind MyRepeater to the  DataSet. MyRepeater is the ID of the
      // Repeater control in the HTML section of the page.
      MyRepeater.DataSource = ds;
      MyRepeater.DataBind();
   }
</script>

<%--  Display the data in the body of the page. --%>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">
   <ASP:Repeater id="MyRepeater" runat="server">
      <HeaderTemplate>
         <Table width="100%" style="font: 8pt verdana">
            <tr style="background-color:DFA894">
               <th>
                  Title
               </th>
               <th>
                  Title ID
               </th>
               <th>
                  Type
               </th>
               <th>
                  Publisher ID
               </th>
               <th>
                  Price
               </th>
            </tr>
      </HeaderTemplate>

      <ItemTemplate>
            <tr style="background-color:FFECD8">
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "title") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem,"title_id") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "type") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, "pub_id") %>
               </td>
               <td>
                  <%# DataBinder.Eval(Container.DataItem, 
                     "price", "{0:c}") %>
               </td>
            </tr>
      </ItemTemplate>

      <FooterTemplate>
         </Table>

      </FooterTemplate>
   </ASP:Repeater>
</body>
</html>

Vea también

Acceso a datos con ASP.NET | Acceso a datos con ADO.NET | System.Web.UI.WebControls (Espacio de nombres) | Repeater (Clase)