ObjectDataSource.FilterParameters Propriedade
Definição
Obtém uma coleção de parâmetros associados a espaços reservados para parâmetros na cadeia de caracteres FilterExpression.Gets a collection of parameters that are associated with any parameter placeholders in the FilterExpression string.
public:
property System::Web::UI::WebControls::ParameterCollection ^ FilterParameters { System::Web::UI::WebControls::ParameterCollection ^ get(); };
[System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)]
public System.Web.UI.WebControls.ParameterCollection FilterParameters { get; }
[<System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)>]
member this.FilterParameters : System.Web.UI.WebControls.ParameterCollection
Public ReadOnly Property FilterParameters As ParameterCollection
Valor da propriedade
Um ParameterCollection que contém um conjunto de parâmetros associados a quaisquer espaços reservados para parâmetro encontrados na propriedade FilterExpression.A ParameterCollection that contains a set of parameters associated with any parameter placeholders found in the FilterExpression property.
- Atributos
Exceções
Se você definir a propriedade FilterExpression, o método Select() não retornará um DataSet ou DataTable.You set the FilterExpression property and the Select() method does not return a DataSet or DataTable.
Exemplos
Esta seção contém dois exemplos de código.This section contains two code examples. O primeiro exemplo de código demonstra como exibir dados filtrados usando um ObjectDataSource objeto para recuperar dados de um objeto comercial de camada intermediária e um GridView controle para exibir os resultados.The first code example demonstrates how to display filtered data using an ObjectDataSource object to retrieve data from a middle-tier business object and a GridView control to display the results. O segundo exemplo de código fornece um exemplo de um objeto comercial de camada intermediária que é usado no primeiro exemplo de código.The second code example provides an example of a middle-tier business object that is used in the first code example.
O exemplo de código a seguir demonstra como exibir dados filtrados usando um ObjectDataSource controle para recuperar dados de um objeto comercial de camada intermediária e um GridView controle para exibir os resultados.The following code example demonstrates how to display filtered data using an ObjectDataSource control to retrieve data from a middle-tier business object and a GridView control to display the results. O ObjectDataSource controle só pode filtrar dados quando o método que recupera os dados os recupera como um DataSet DataTable objeto ou.The ObjectDataSource control can filter data only when the method that retrieves the data retrieves it as a DataSet or DataTable object. Por esse motivo, a SelectMethod propriedade identifica um método de objeto comercial que recupera dados como um DataSet .For this reason, the SelectMethod property identifies a business object method that retrieves data as a DataSet.
O exemplo de código consiste em um TextBox controle, um GridView controle, o ObjectDataSource controle e um botão de envio .The code example consists of a TextBox control, a GridView control, the ObjectDataSource control, and a Submit button. Por padrão, o TextBox é preenchido com o nome de um dos funcionários da Northwind Traders.By default, the TextBox is populated with the name of one of the Northwind Traders employees. O GridView exibe informações sobre o funcionário que é identificado pelo nome no TextBox .The GridView displays information about the employee that is identified by the name in the TextBox. Para recuperar dados de outro funcionário, no TextBox , insira o nome completo do funcionário e, em seguida, clique no botão Enviar .To retrieve data on another employee, in the TextBox, enter the full name of the employee, and then click the Submit button.
A FilterExpression propriedade especifica uma expressão que é usada para filtrar os dados recuperados pela SelectMethod propriedade.The FilterExpression property specifies an expression that is used to filter the data that is retrieved by the SelectMethod property. Ele usa espaços reservados de parâmetro que são avaliados para os parâmetros contidos na FilterParameters coleção.It uses parameter placeholders that are evaluated to the parameters that are contained in the FilterParameters collection. Neste exemplo, o espaço reservado de parâmetro é limitado por aspas simples porque o tipo do parâmetro é um tipo de cadeia de caracteres que pode conter espaços.In this example, the parameter placeholder is bounded by single quotation marks because the type of the parameter is a string type that might contain spaces. Se o tipo do parâmetro for um tipo numérico ou de data, as aspas delimitadoras não serão necessárias.If the type of the parameter is a numeric or date type, bounding quotation marks are not required. A FilterParameters coleção contém um parâmetro, um FormParameter objeto associado ao TextBox controle.The FilterParameters collection contains one parameter, a FormParameter object that is bound to the TextBox control.
Importante
Você deve validar qualquer valor de parâmetro de filtro que você recebe do cliente.You should validate any filter parameter value that you receive from the client. O tempo de execução simplesmente substitui o valor do parâmetro na expressão de filtro e o aplica ao DataView objeto retornado pelo Select método.The runtime simply substitutes the parameter value into the filter expression and applies it to the DataView object that is returned by the Select method. Se você estiver usando a FilterExpression propriedade como uma medida de segurança para limitar o número de itens retornados, você deverá validar os valores de parâmetro antes que a filtragem ocorra.If you are using the FilterExpression property as a security measure to limit the number of items that are returned, you must validate the parameter values before the filtering occurs.
<%@ 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">
<script runat="server">
protected void ObjectDataSource1_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
{
if (Textbox1.Text == "")
{
e.ParameterValues.Clear();
e.ParameterValues.Add("FullName", "Nancy Davolio");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<p>Show all users with the following name.</p>
<asp:textbox id="Textbox1" runat="server" text="Nancy Davolio" />
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1"
autogeneratecolumns="False">
<columns>
<asp:boundfield headertext="ID" datafield="EmpID" />
<asp:boundfield headertext="Name" datafield="FullName" />
<asp:boundfield headertext="Street Address" datafield="Address" />
</columns>
</asp:gridview>
<!-- Security Note: The ObjectDataSource uses a FormParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployeesAsDataSet"
typename="Samples.AspNet.CS.EmployeeLogic"
filterexpression="FullName='{0}'" OnFiltering="ObjectDataSource1_Filtering">
<filterparameters>
<asp:formparameter name="FullName" formfield="Textbox1" defaultvalue="Nancy Davolio" />
</filterparameters>
</asp:objectdatasource>
<p><asp:button id="Button1" runat="server" text="Search" /></p>
</form>
</body>
</html>
<%@ 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">
<script runat="server">
Protected Sub ObjectDataSource1_Filtering(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceFilteringEventArgs)
If Textbox1.Text = "" Then
e.ParameterValues.Clear()
e.ParameterValues.Add("FullName", "Nancy Davolio")
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - VB Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<p>Show all users with the following name.</p>
<asp:textbox id="Textbox1" runat="server" text="Nancy Davolio" />
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1"
autogeneratecolumns="False">
<columns>
<asp:boundfield headertext="ID" datafield="EmpID" />
<asp:boundfield headertext="Name" datafield="FullName" />
<asp:boundfield headertext="Street Address" datafield="Address" />
</columns>
</asp:gridview>
<!-- Security Note: The ObjectDataSource uses a FormParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployeesAsDataSet"
typename="Samples.AspNet.VB.EmployeeLogic"
filterexpression="FullName='{0}'" OnFiltering="ObjectDataSource1_Filtering">
<filterparameters>
<asp:formparameter name="FullName" formfield="Textbox1" defaultvalue="Nancy Davolio" />
</filterparameters>
</asp:objectdatasource>
<p><asp:button id="Button1" runat="server" text="Search" /></p>
</form>
</body>
</html>
O exemplo de código a seguir fornece um exemplo de um objeto comercial de camada intermediária que o exemplo de código anterior usa.The following code example provides an example of a middle-tier business object that the preceding code example uses. O exemplo de código consiste em duas classes básicas:The code example consists of two basic classes:
A
EmployeeLogicclasse, que é uma classe que encapsula a lógica de negócios.TheEmployeeLogicclass, which is a class that encapsulates business logic.A
NorthwindEmployeeclasse, que é uma classe de modelo que contém apenas a funcionalidade básica necessária para carregar e persistir dados da camada de dados.TheNorthwindEmployeeclass, which is a model class that contains only the basic functionality that is required to load and persist data from the data tier.
Para simplificar, a EmployeeLogic classe cria um conjunto estático de dados, em vez de recuperar os dados de uma camada de dados.For simplicity, the EmployeeLogic class creates a static set of data, rather than retrieving the data from a data tier. Ele também é útil para este exemplo, porque o exemplo se baseia em você para fornecer o nome completo de um funcionário da Northwind Traders para demonstrar a filtragem.It is also helpful for this example, because the sample relies on you to provide the full name of a Northwind Traders employee to demonstrate filtering. Para obter um exemplo funcional completo, você deve compilar e usar essas classes com os exemplos de código de Web Forms que são fornecidos.For a complete working example, you must compile and use these classes with the Web Forms code examples that are provided.
namespace Samples.AspNet.CS {
using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations you can perform on a NorthwindEmployee object.
//
public class EmployeeLogic {
// Returns a collection of NorthwindEmployee objects.
public static ICollection GetAllEmployees () {
ArrayList data = new ArrayList();
data.Add(new NorthwindEmployee(1,"Nancy","Davolio","507 - 20th Ave. E. Apt. 2A"));
data.Add(new NorthwindEmployee(2,"Andrew","Fuller","908 W. Capital Way"));
data.Add(new NorthwindEmployee(3,"Janet","Leverling","722 Moss Bay Blvd."));
data.Add(new NorthwindEmployee(4,"Margaret","Peacock","4110 Old Redmond Rd."));
data.Add(new NorthwindEmployee(5,"Steven","Buchanan","14 Garrett Hill"));
data.Add(new NorthwindEmployee(6,"Michael","Suyama","Coventry House Miner Rd."));
data.Add(new NorthwindEmployee(7,"Robert","King","Edgeham Hollow Winchester Way"));
return data;
}
public static NorthwindEmployee GetEmployee(object anID) {
ArrayList data = GetAllEmployees() as ArrayList;
int empID = Int32.Parse(anID.ToString());
return data[empID] as NorthwindEmployee;
}
//
// To support basic filtering, the employees cannot
// be returned as an array of objects, rather as a
// DataSet of the raw data values.
public static DataSet GetAllEmployeesAsDataSet () {
ICollection employees = GetAllEmployees();
DataSet ds = new DataSet("Table");
// Create the schema of the DataTable.
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("EmpID", typeof(int)); dt.Columns.Add(dc);
dc = new DataColumn("FullName",typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Address", typeof(string)); dt.Columns.Add(dc);
// Add rows to the DataTable.
DataRow row;
foreach (NorthwindEmployee ne in employees) {
row = dt.NewRow();
row["EmpID"] = ne.EmpID;
row["FullName"] = ne.FullName;
row["Address"] = ne.Address;
dt.Rows.Add(row);
}
// Add the complete DataTable to the DataSet.
ds.Tables.Add(dt);
return ds;
}
}
public class NorthwindEmployee {
public NorthwindEmployee (int anID,
string aFirstName,
string aLastName,
string anAddress) {
ID = anID;
firstName = aFirstName;
lastName = aLastName;
address = anAddress;
}
private object ID;
public string EmpID {
get { return ID.ToString(); }
}
private string lastName;
public string LastName {
get { return lastName; }
set { lastName = value; }
}
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
public string FullName {
get { return FirstName + " " + LastName; }
}
private string address;
public string Address {
get { return address; }
set { address = value; }
}
}
}
Imports System.Collections
Imports System.Data
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB
'
' EmployeeLogic is a stateless business object that encapsulates
' the operations you can perform on a NorthwindEmployee object.
'
Public Class EmployeeLogic
' Returns a collection of NorthwindEmployee objects.
Public Shared Function GetAllEmployees() As ICollection
Dim data As New ArrayList()
data.Add(New NorthwindEmployee(1, "Nancy", "Davolio", "507 - 20th Ave. E. Apt. 2A"))
data.Add(New NorthwindEmployee(2, "Andrew", "Fuller", "908 W. Capital Way"))
data.Add(New NorthwindEmployee(3, "Janet", "Leverling", "722 Moss Bay Blvd."))
data.Add(New NorthwindEmployee(4, "Margaret", "Peacock", "4110 Old Redmond Rd."))
data.Add(New NorthwindEmployee(5, "Steven", "Buchanan", "14 Garrett Hill"))
data.Add(New NorthwindEmployee(6, "Michael", "Suyama", "Coventry House Miner Rd."))
data.Add(New NorthwindEmployee(7, "Robert", "King", "Edgeham Hollow Winchester Way"))
Return data
End Function 'GetAllEmployees
Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
Dim data As ArrayList = CType(GetAllEmployees(), ArrayList)
Dim empID As Integer = Int32.Parse(anID.ToString())
Return CType(data(empID),NorthwindEmployee)
End Function 'GetEmployee
' To support basic filtering, the employees cannot
' be returned as an array of objects, rather as a
' DataSet of the raw data values.
Public Shared Function GetAllEmployeesAsDataSet() As DataSet
Dim employees As ICollection = GetAllEmployees()
Dim ds As New DataSet("Table")
' Create the schema of the DataTable.
Dim dt As New DataTable()
Dim dc As DataColumn
dc = New DataColumn("EmpID", GetType(Integer))
dt.Columns.Add(dc)
dc = New DataColumn("FullName", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Address", GetType(String))
dt.Columns.Add(dc)
' Add rows to the DataTable.
Dim row As DataRow
Dim ne As NorthwindEmployee
For Each ne In employees
row = dt.NewRow()
row("EmpID") = ne.EmpID
row("FullName") = ne.FullName
row("Address") = ne.Address
dt.Rows.Add(row)
Next
' Add the complete DataTable to the DataSet.
ds.Tables.Add(dt)
Return ds
End Function 'GetAllEmployeesAsDataSet
End Class
Public Class NorthwindEmployee
Public Sub New(anID As Integer, aFirstName As String, aLastName As String, anAddress As String)
ID = anID
Me.aFirstName = aFirstName
Me.aLastName = aLastName
Me.aAddress = anAddress
End Sub
Private ID As Object
Public ReadOnly Property EmpID() As String
Get
Return ID.ToString()
End Get
End Property
Private aLastName As String
Public Property LastName() As String
Get
Return aLastName
End Get
Set
aLastName = value
End Set
End Property
Private aFirstName As String
Public Property FirstName() As String
Get
Return aFirstName
End Get
Set
aFirstName = value
End Set
End Property
Public ReadOnly Property FullName() As String
Get
Return FirstName & " " & LastName
End Get
End Property
Private aAddress As String
Public Property Address() As String
Get
Return aAddress
End Get
Set
aAddress = value
End Set
End Property
End Class
End Namespace
Comentários
O ObjectDataSource controle dá suporte à filtragem de dados somente quando o Select método retorna um DataSet DataTable objeto ou.The ObjectDataSource control supports filtering data only when the Select method returns a DataSet or DataTable object.
A sintaxe usada para o FilterExpression é uma expressão de estilo de cadeia de caracteres de formato.The syntax that is used for the FilterExpression is a format string-style expression. A sintaxe de expressão de filtro é a mesma sintaxe aceita pela Expression propriedade.The filter expression syntax is the same syntax that is accepted by the Expression property. Se você adicionar parâmetros à FilterParameters coleção, também poderá incluir espaços reservados de cadeia de caracteres de formato.If you add parameters to the FilterParameters collection, you can also include format string placeholders. Por exemplo, inclua "{0}" na expressão para substituir os valores de parâmetro.For example, include "{0}" in the expression to substitute for parameter values. Os espaços reservados são substituídos de acordo com o índice do parâmetro na FilterParameters coleção.The placeholders are replaced according to the index of the parameter in the FilterParameters collection.
Você pode incluir parâmetros na FilterExpression propriedade.You can include parameters in the FilterExpression property. Se o parâmetro for uma cadeia de caracteres ou um tipo de caractere, coloque o parâmetro entre aspas simples.If the parameter is a string or character type, enclose the parameter in single quotation marks. Aspas não serão necessárias se o parâmetro for um tipo numérico.Quotation marks are not required if the parameter is a numeric type.
A FilterParameters propriedade recupera a FilterParameters Propriedade contida pelo ObjectDataSourceView objeto que está associado ao ObjectDataSource controle.The FilterParameters property retrieves the FilterParameters property that is contained by the ObjectDataSourceView object that is associated with the ObjectDataSource control.
Aplica-se a
Confira também
- FilterExpression
- Filtering
- {1>Controles de servidor Web de fonte de dados<1}Data Source Web Server Controls
- Visão geral do controle ObjectDataSourceObjectDataSource Control Overview
- {1>Criando um objeto de origem de controle ObjectDataSource<1}Creating an ObjectDataSource Control Source Object