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 sobrecargado Eval de esta clase en la sintaxis de enlace de datos en una página web de ASP.NET. Esto proporciona una sintaxis más fácil de trabajar con que el enlace de datos estándar. Sin embargo, dado que DataBinder.Eval proporciona 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 formularios web Forms, consulte Enlace de modelos y formularios web.

Constructores

Nombre Description
DataBinder()

Inicializa una nueva instancia de la clase DataBinder.

Propiedades

Nombre Description
EnableCaching

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

Métodos

Nombre Description
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
Eval(Object, String, String)

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

Eval(Object, String)

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

GetDataItem(Object, Boolean)

Recupera el elemento de datos declarado de un objeto, lo que indica que se ha realizado correctamente o no.

GetDataItem(Object)

Recupera el elemento de datos declarado de un objeto.

GetHashCode()

Actúa como la función hash predeterminada.

(Heredado de Object)
GetIndexedPropertyValue(Object, String, String)

Recupera el valor de la propiedad especificada para el contenedor especificado y, a continuación, da formato a los resultados.

GetIndexedPropertyValue(Object, String)

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

GetPropertyValue(Object, String, String)

Recupera el valor de la propiedad especificada del objeto especificado y, a continuación, da formato a los resultados.

GetPropertyValue(Object, String)

Recupera el valor de la propiedad especificada del objeto especificado.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsBindableType(Type)

Determina si se puede enlazar el tipo de datos especificado.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también