DataBinder Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece suporte a designers de desenvolvimento rápido de aplicações (RAD) para gerar e analisar sintaxe de expressões de ligação de dados. Esta classe não pode ser herdada.
public ref class DataBinder sealed
public sealed class DataBinder
type DataBinder = class
Public NotInheritable Class DataBinder
- Herança
-
DataBinder
Exemplos
O exemplo seguinte usa o método estático GetPropertyValue para preencher os campos de um Repeater controlo usando um ArrayList de Product objetos. O Eval método podia ser aplicado com a mesma sintaxe, mas não teria um desempenho tão rápido.
Este exemplo utiliza uma classe personalizada Product que expõe uma propriedade de cadeia Model e uma propriedade 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>
O código seguinte é a classe personalizada Product . Este código deve ser incluído num ficheiro de classes separado no diretório App_Code, como Product.cs ou 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
Observações
Pode usar o método saturado estático Eval desta classe na sintaxe de ligação de dados numa página web ASP.NET. Isto proporciona uma sintaxe mais fácil de trabalhar do que a ligação de dados padrão. No entanto, por DataBinder.Eval fornecer conversão automática de tipos, pode resultar em desempenho mais lento.
Para mais informações sobre ASP.NET data binding, expressões e sintaxe, veja Binding to Databases e Data-Binding Expressions Overview.
A partir do .NET Framework 4.5, podes usar a ligação de modelos para simplificar algumas das tarefas que tinhas de realizar através da ligação de dados em versões anteriores. Para uma série de tutoriais sobre a utilização de encadernação de modelos com Web Forms, veja Encadernação de Modelos e Web Formulários.
Construtores
| Name | Description |
|---|---|
| DataBinder() |
Inicializa uma nova instância da DataBinder classe. |
Propriedades
| Name | Description |
|---|---|
| EnableCaching |
Recebe ou define um valor que indica se a cache de dados está ativada em tempo de execução. |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| Eval(Object, String, String) |
Avalia expressões de ligação de dados em tempo de execução e formata o resultado como uma cadeia. |
| Eval(Object, String) |
Avalia expressões de ligação de dados em tempo de execução. |
| GetDataItem(Object, Boolean) |
Recupera o elemento de dados declarado de um objeto, indicando sucesso ou falha. |
| GetDataItem(Object) |
Recupera o item de dados declarado de um objeto. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetIndexedPropertyValue(Object, String, String) |
Recupera o valor da propriedade especificada para o contentor especificado e depois formata os resultados. |
| GetIndexedPropertyValue(Object, String) |
Recupera o valor de uma propriedade do contentor especificado e do caminho de navegação. |
| GetPropertyValue(Object, String, String) |
Recupera o valor da propriedade especificada do objeto especificado e depois formata os resultados. |
| GetPropertyValue(Object, String) |
Recupera o valor da propriedade especificada do objeto especificado. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsBindableType(Type) |
Determina se o tipo de dado especificado pode ser limitado. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |