ObjectDataSource.FilterExpression 属性

定义

获取或设置当调用由 SelectMethod 属性指定的方法时应用的筛选表达式。Gets or sets a filtering expression that is applied when the method that is specified by the SelectMethod property is called.

public:
 property System::String ^ FilterExpression { System::String ^ get(); void set(System::String ^ value); };
public string FilterExpression { get; set; }
member this.FilterExpression : string with get, set
Public Property FilterExpression As String

属性值

一个字符串,表示在使用由 SelectMethod 属性标识的方法或函数检索数据时应用的筛选表达式。A string that represents a filtering expression that is applied when data is retrieved by using the method or function identified by the SelectMethod property.

异常

设置了 FilterExpression 属性,但 Select() 方法没有返回 DataSetDataTableThe FilterExpression property was set and the Select() method does not return a DataSet or DataTable.

示例

下面的代码示例演示如何使用ObjectDataSource控件显示筛选的数据, 以便从中间层业务对象检索数据GridView和显示结果的控件。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. 仅当检索数据的方法将其检索DataSet为或DataTable对象时,控件才能筛选数据。ObjectDataSourceThe ObjectDataSource control can filter data only when the method that retrieves the data retrieves it as a DataSet or DataTable object. 出于此原因, SelectMethod属性标识将数据DataSet作为检索的业务对象方法。For this reason, the SelectMethod property identifies a business object method that retrieves data as a DataSet.

TextBox代码示例包含一个控件、一个GridView控件、 ObjectDataSource一个控件和一个提交按钮。The code example consists of a TextBox control, a GridView control, the ObjectDataSource control, and a Submit button. 默认情况下, TextBox将使用其中一个 Northwind 商贸员工的名称填充。By default, the TextBox is populated with the name of one of the Northwind Traders employees. 显示由中的名称标识的员工的相关信息。 TextBox GridViewThe GridView displays information about the employee that is identified by the name in the TextBox. 若要检索另一个雇员的数据, 请在中TextBox输入雇员的全名, 然后单击 "提交" 按钮。To retrieve data on another employee, enter the full name of the employee in the TextBox, and then click the Submit button.

属性指定一个表达式, 该表达式用于筛选由SelectMethod属性指定的方法检索的数据。 FilterExpressionThe FilterExpression property specifies an expression that is used to filter the data that is retrieved by the method that is specified by the SelectMethod property. 它使用计算结果为FilterParameters集合中包含的参数的参数占位符。It uses parameter placeholders that are evaluated to the parameters that are contained in the FilterParameters collection. 在此示例中, 参数占位符由单引号界定, 因为参数的类型是可能包含空格的字符串类型。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. 如果参数的类型是数值或日期类型, 则不需要用到边界引号。If the type of the parameter is a numeric or date type, bounding quotation marks are not required.

重要

此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。This example has a text box that accepts user input, which is a potential security threat. 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 有关详细信息,请参阅脚本侵入概述For more information, see Script Exploits Overview.

<%@ 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>

下面的代码示例提供了前面的代码示例使用的中间层业务对象的示例。The following code example provides an example of a middle-tier business object that the preceding code example uses. 此代码示例包含两个基本类:The code example consists of two basic classes:

  • EmployeeLogic类, 该类是封装业务逻辑的类。The EmployeeLogic class, which is a class that encapsulates business logic.

  • NorthwindEmployee类, 该类是一个模型类, 其中只包含从数据层加载和保存数据所需的基本功能。The NorthwindEmployee class, which is a model class that contains only the basic functionality that is required to load and persist data from the data tier.

为简单起见, EmployeeLogic类创建了静态数据集, 而不是从数据层检索数据。For simplicity, the EmployeeLogic class creates a static set of data, rather than retrieving the data from a data tier. 它在此示例中也很有帮助, 因为示例需要提供 Northwind 商贸员工的全名才能演示筛选。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. 对于完整的工作示例, 必须使用所提供的 Web 窗体代码示例来编译并使用这些类。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

注解

ObjectDataSource 当方法返回DataSetDataTable对象时, 控件才支持筛选数据。 SelectThe ObjectDataSource control supports filtering data only when the Select method returns a DataSet or DataTable object.

用于FilterExpression属性的语法是格式字符串样式表达式。The syntax that is used for the FilterExpression property is a format string-style expression. 筛选表达式语法与Expression属性接受的语法相同。The filter expression syntax is the same syntax that is accepted by the Expression property. 如果向FilterParameters集合添加参数, 还可以包含格式字符串占位符。If you add parameters to the FilterParameters collection, you can also include format string placeholders. 例如, 在要"{0}"替换参数值的表达式中包含。For example, include "{0}" in the expression to substitute for parameter values. 根据FilterParameters集合中参数的索引替换占位符。The placeholders are replaced according to the index of the parameter in the FilterParameters collection.

可以在FilterExpression属性中包含参数。You can include parameters in the FilterExpression property. 如果参数的类型是字符串或字符类型, 则将参数括在单引号内。If the type of the parameter is a string or character type, enclose the parameter in single quotation marks. 如果参数是数值类型, 则不需要引号。Quotation marks are not required if the parameter is a numeric type.

集合包含为FilterExpression属性中的占位符计算的参数。 FilterParametersThe FilterParameters collection contains the parameters that are evaluated for the placeholders that are found in the FilterExpression property.

属性委托ObjectDataSourceView FilterExpression给与ObjectDataSource控件相关联的对象的属性。 FilterExpressionThe FilterExpression property delegates to the FilterExpression property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.

备注

应该验证从客户端接收的任何筛选器参数值。You should validate any filter parameter value that you receive from the client. 运行时只需将参数值替换为筛选表达式, 并将其DataSet应用于DataTable Select方法返回的或对象。The runtime simply substitutes the parameter value into the filter expression and applies it to the DataSet or DataTable object that is returned by the Select method. 如果使用FilterExpression属性作为安全措施来限制返回的项目数, 则必须在进行筛选之前验证参数值。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.

适用于

另请参阅