Share via


Establecer enlaces a datos utilizando un control de origen de datos

Actualización: noviembre 2007

Los controles de origen de datos expanden las funciones de controles enlazados a datos como GridView, FormView y los controles DetailsView. Juntos, los controles de origen de datos y los enlazados a datos permiten recuperar, modificar, paginar, ordenar y filtrar datos de diferentes orígenes de datos con menos código o sin código.

Enlaces utilizando la propiedad DataSourceID

Puede trabajar con datos de un control enlazado a datos enlazando el control a un control de origen de datos como ObjectDataSource o SqlDataSource. El control de origen de datos conecta a un origen de datos como una base de datos o el objeto de nivel medio y, a continuación, recupera o actualiza los datos. El control enlazado a datos puede utilizar entonces este dato. Para realizar el enlace, establezca la propiedad DataSourceID del control enlazado a datos para señalar a un control de origen de datos. Cuando un control enlazado a datos se enlaza a un control de origen de datos, apenas se necesita escribir código o nada para realizar operaciones con datos, porque el control enlazado a datos puede aprovecharse automáticamente de los servicios de datos proporcionados por el control de origen de datos.

Nota:

En versiones anteriores de ASP.NET, los controles enlazados se enlazaron a datos utilizando la propiedad DataSource y es necesario que escriba código que controle las operaciones de mostrar, paginar, ordenar, editar y eliminar datos. Aunque todavía puede enlazar controles a datos utilizando la propiedad DataSource (y el código existente), ahora puede realizar enlaces utilizando la propiedad DataSourceID en su lugar.

El ejemplo de código siguiente muestra un control FormView enlazado a un control SqlDataSource para mostrar los datos de una base de datos.

<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" >
      <h3>FormView Example</h3>
        <table cellspacing="10"> 
          <tr>               
            <td valign="top">

              <asp:FormView ID="ProductsFormView"
                DataSourceID="ProductsSqlDataSource"
                AllowPaging="true"
                >

                <HeaderStyle forecolor="white" backcolor="Blue" />                

                <ItemTemplate>
                  <table>
                    <tr>
                      <td align="right"><b>Product ID:</b></td>
                      <td><asp:Label id="ProductIDLabel"  Text='<%# Eval("ProductID") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Product Name:</b></td>
                      <td><asp:Label id="ProductNameLabel"  Text='<%# Eval("ProductName") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Category ID:</b></td>
                      <td><asp:Label id="CategoryIDLabel"  Text='<%# Eval("CategoryID") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Quantity Per Unit:</b></td>
                      <td><asp:Label id="QuantityPerUnitLabel"  Text='<%# Eval("QuantityPerUnit") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Unit Price:</b></td>
                      <td><asp:Label id="UnitPriceLabel"  Text='<%# Eval("UnitPrice") %>' /></td>
                    </tr>
                  </table>                 
                </ItemTemplate>

                <PagerTemplate>
                  <table>
                    <tr>
                      <td><asp:LinkButton ID="FirstButton" CommandName="Page" CommandArgument="First" Text="<<" RunAt="server"/></td>
                      <td><asp:LinkButton ID="PrevButton"  CommandName="Page" CommandArgument="Prev"  Text="<"  RunAt="server"/></td>
                      <td><asp:LinkButton ID="NextButton"  CommandName="Page" CommandArgument="Next"  Text=">"  RunAt="server"/></td>
                      <td><asp:LinkButton ID="LastButton"  CommandName="Page" CommandArgument="Last"  Text=">>" RunAt="server"/></td>
                    </tr>
                  </table>
                </PagerTemplate>

              </asp:FormView>

            </td>
          </tr>
        </table>

        <asp:SqlDataSource ID="ProductsSqlDataSource" 
          SelectCommand="SELECT * FROM [Products]" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server"/>

      </form>
  </body>
</html>
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" >
      <h3>FormView Example</h3>
        <table cellspacing="10"> 
          <tr>               
            <td valign="top">

              <asp:FormView ID="ProductsFormView"
                DataSourceID="ProductsSqlDataSource"
                AllowPaging="true"
                >

                <HeaderStyle forecolor="white" backcolor="Blue" />                

                <ItemTemplate>
                  <table>
                    <tr>
                      <td align="right"><b>Product ID:</b></td>
                      <td><asp:Label id="ProductIDLabel"  Text='<%# Eval("ProductID") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Product Name:</b></td>
                      <td><asp:Label id="ProductNameLabel"  Text='<%# Eval("ProductName") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Category ID:</b></td>
                      <td><asp:Label id="CategoryIDLabel"  Text='<%# Eval("CategoryID") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Quantity Per Unit:</b></td>
                      <td><asp:Label id="QuantityPerUnitLabel"  Text='<%# Eval("QuantityPerUnit") %>' /></td>
                    </tr>
                    <tr>
                      <td align="right"><b>Unit Price:</b></td>
                      <td><asp:Label id="UnitPriceLabel"  Text='<%# Eval("UnitPrice") %>' /></td>
                    </tr>
                  </table>                 
                </ItemTemplate>

                <PagerTemplate>
                  <table>
                    <tr>
                      <td><asp:LinkButton ID="FirstButton" CommandName="Page" CommandArgument="First" Text="<<" RunAt="server"/></td>
                      <td><asp:LinkButton ID="PrevButton"  CommandName="Page" CommandArgument="Prev"  Text="<"  RunAt="server"/></td>
                      <td><asp:LinkButton ID="NextButton"  CommandName="Page" CommandArgument="Next"  Text=">"  RunAt="server"/></td>
                      <td><asp:LinkButton ID="LastButton"  CommandName="Page" CommandArgument="Last"  Text=">>" RunAt="server"/></td>
                    </tr>
                  </table>
                </PagerTemplate>

              </asp:FormView>

            </td>
          </tr>
        </table>

        <asp:SqlDataSource ID="ProductsSqlDataSource" 
          SelectCommand="SELECT ProductID, ProductName, CategoryID, QuantityPerUnit, UnitPrice FROM [Products]" 
          connectionstring="<%$ ConnectionStrings:NorthwindConnection %>" 
          RunAt="server"/>

      </form>
  </body>
</html>

Para obtener más información sobre controles de origen de datos, vea Controles de servidor Web de orígenes de datos.

Seleccionar datos

El propio control determina la manera en la que un control de origen de datos recupera los datos. El control ObjectDataSource lee los datos llamando al método especificado en la propiedad SelectMethod. El ejemplo de código siguiente muestra un control ObjectDataSource que devuelve datos mediante el método GetAllEmployees de la clase EmployeeLogic:

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - Visual Basic Example</title>
  </head>
  <body>
    <form id="Form1" method="post" >

        <asp:gridview
          id="GridView1"
          
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.VB.EmployeeLogic" />

    </form>
  </body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" >

        <asp:gridview
          id="GridView1"
          
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.CS.EmployeeLogic" />

    </form>
  </body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Page language="VJ#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VJ# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" >

        <asp:gridview
          id="GridView1"
          
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.JSL.EmployeeLogic" />

    </form>
  </body>
</html>

Para obtener más información, vea Información general sobre el control de servidor web ObjectDataSource.

Los controles SqlDataSource y AccessDataSource selecciona los datos ejecutando una consulta SQL especificada en la propiedad SelectCommand. El ejemplo de código siguiente muestra un control SqlDataSource que devuelve los datos de la tabla Empleados de la base de datos de ejemplo Northwind:

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head >
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" >
      <asp:SqlDataSource
          id="SqlDataSource1"
          
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

    </form>
  </body>
</html>

Para obtener más información, vea Seleccionar datos mediante el control SqlDataSource.

XmlDataSource no le permite seleccionar los elementos específicos de los datos XML de origen. Sin embargo, puede especificar un filtro utilizando la propiedad XPath. Para obtener más información, vea Filtrar datos mediante el control XmlDataSource.

Modificar datos

Los controles ObjectDataSource y SqlDataSource admiten la modificación de datos enlazados. Para obtener más información, vea Modificar datos mediante controles de origen de datos.

Vea también

Otros recursos

Controles de servidor Web de orígenes de datos