DataBinder Clase

Definición

Proporciona compatibilidad con diseñadores de desarrollo rápido de aplicaciones (RAD) para generar y analizar la sintaxis de expresiones de enlace de datos. Esta clase no puede heredarse.

public ref class DataBinder sealed
public sealed class DataBinder
type DataBinder = class
Public NotInheritable Class DataBinder
Herencia
DataBinder

Ejemplos

En el ejemplo siguiente se usa el método estático GetPropertyValue para rellenar los campos de un Repeater control mediante un ArrayList de Product objetos . El Eval método se podría aplicar con la misma sintaxis, pero no funcionaría tan rápidamente.

En este ejemplo se usa una clase personalizada Product que expone una propiedad de cadena Model y una propiedad numérica UnitPrice .

<%@ Page Language="C#" %>
<%@ Import Namespace="ASPSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void  Page_Load(object sender, EventArgs e)
{
        // Create and populate an ArrayList to store the products.
        ArrayList ProductList = new ArrayList();
        ProductList.Add(new Product("Standard", 99.95));
        ProductList.Add(new Product("Deluxe", 159.95));

        // Bind the array list to Repeater
        ListRepeater.DataSource = ProductList;
        ListRepeater.DataBind();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>DataBinder Example</title>
</head>
<body>
<form id="Form2" runat="server">
<table>
<asp:Repeater id="ListRepeater" runat="server">
    <HeaderTemplate>
    <tr>
        <th style="width:50; text-align:left">Model</th>
        <th style="width:100; text-align:right">Unit Price</th>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr>
        <!-- Databind to the Product information using the DataBinder methods. 
             The Container.DataItem refers to the ArrayList object bound to 
             the ASP:Repeater in the Page Load event. -->
        <td>
            <%#DataBinder.GetPropertyValue(Container.DataItem, "Model")%>
        </td>
        <!-- Format the UnitPrice as currency. ({0:c}) -->
        <td style="text-align:right">
            <%#DataBinder.GetPropertyValue(Container.DataItem,
                         "UnitPrice", "{0:c}")%>
        </td>
    </tr>
    </ItemTemplate>
</asp:Repeater>
</table>
</form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ Import Namespace="ASPSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        ' Create and populate an ArrayList to store the products.
        Dim ProductList As New ArrayList
        ProductList.Add(New Product("Standard", 99.95))
        ProductList.Add(New Product("Deluxe", 159.95))

        ' Bind the array list to Repeater
        ListRepeater.DataSource = ProductList
        ListRepeater.DataBind()

    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>DataBinder Example</title>
</head>
<body>
<form id="Form2" runat="server">
<table>
<asp:Repeater id="ListRepeater" runat="server">
    <HeaderTemplate>
    <tr>
        <th style="width:50; text-align:left">Model</th>
        <th style="width:100; text-align:right">Unit Price</th>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr>
        <!-- Databind to the Product information using the DataBinder methods. 
             The Container.DataItem refers to the ArrayList object bound to 
             the ASP:Repeater in the Page Load event. -->
        <td>
            <%#DataBinder.GetPropertyValue(Container.DataItem, "Model")%>
        </td>
        <!-- Format the UnitPrice as currency. ({0:c}) -->
        <td style="text-align:right">
            <%#DataBinder.GetPropertyValue(Container.DataItem, _
                         "UnitPrice", "{0:c}")%>
        </td>
    </tr>
    </ItemTemplate>
</asp:Repeater>
</table>
</form>
</body>
</html>

El código siguiente es la clase personalizada Product . Este código debe incluirse en un archivo de clase independiente en el directorio App_Code, como Product.cs o Product.vb.

namespace ASPSample
{

    public class Product
    {
        string _Model;
        double _UnitPrice;

        public Product(string Model, double UnitPrice)
        {
            _Model = Model;
            _UnitPrice = UnitPrice;
        }

        // The product Model.
        public string Model
        {
            get {return _Model;}
            set {_Model = value;}
        }
            
        // The price of the each product.
        public double UnitPrice
        {
            get {return _UnitPrice;}
            set {_UnitPrice = value;}
        }
    }
}
Namespace ASPSample

    Public Class Product
        Private _Model As String
        Private _UnitPrice As Double

        ' The product Model.
        Public Property Model() As String
            Get
                Return _Model
            End Get
            Set(ByVal Value As String)
                _Model = Value
            End Set
        End Property

        ' The price of the each product.
        Public Property UnitPrice() As Double
            Get
                Return _UnitPrice
            End Get
            Set(ByVal Value As Double)
                _UnitPrice = Value
            End Set
        End Property


        Public Sub New(ByVal Model As String, ByVal UnitPrice As Double)
            _Model = Model
            _UnitPrice = UnitPrice
        End Sub

    End Class

End Namespace

Comentarios

Puede usar el método estático Eval sobrecargado de esta clase en la sintaxis de enlace de datos en una página web de ASP.NET. Esto proporciona una sintaxis más sencilla con la que funciona que el enlace de datos estándar. Sin embargo, dado que DataBinder.Eval proporciona la conversión automática de tipos, puede dar lugar a un rendimiento más lento.

Para obtener más información sobre ASP.NET enlace de datos, expresiones y sintaxis, vea Binding to Databases and Data-Binding Expressions Overview.

A partir de .NET Framework 4.5, puede usar el enlace de modelos para simplificar algunas de las tareas que tenía que realizar a través del enlace de datos en versiones anteriores. Para ver una serie de tutoriales sobre el uso del enlace de modelos con Web Forms, consulte Enlace de modelos y Web Forms.

Constructores

DataBinder()

Inicializa una nueva instancia de la clase DataBinder.

Propiedades

EnableCaching

Obtiene o establece un valor que indica si está habilitado el almacenamiento de datos en caché en tiempo de ejecución.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
Eval(Object, String)

Evalúa las expresiones de enlace de datos en tiempo de ejecución.

Eval(Object, String, String)

Evalúa expresiones de enlace de datos en tiempo de ejecución y da formato de cadena al resultado.

GetDataItem(Object)

Recupera el elemento de datos declarado de un objeto.

GetDataItem(Object, Boolean)

Recupera el elemento de datos declarado de un objeto e indica si se ha realizado correctamente o no.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetIndexedPropertyValue(Object, String)

Recupera el valor de una propiedad del contenedor y ruta de navegación especificados.

GetIndexedPropertyValue(Object, String, String)

Recupera el valor de la propiedad especificada del contenedor indicado y, a continuación, da formato al resultado.

GetPropertyValue(Object, String)

Recupera el valor de la propiedad especificada del objeto indicado.

GetPropertyValue(Object, String, String)

Recupera el valor de la propiedad especificada del objeto indicado y, a continuación, da formato al resultado.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsBindableType(Type)

Determina si el tipo de datos especificado se puede enlazar.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también