Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

ObjectDataSource.FilterExpression Property

Gets or sets a filtering expression that is applied when the method that is specified by the SelectMethod property is called.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
public string FilterExpression { get; set; }
<asp:ObjectDataSource FilterExpression="String" />

Property Value

Type: System.String
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.
ExceptionCondition
NotSupportedException

The FilterExpression property was set and the Select method does not return a DataSet or DataTable.

The ObjectDataSource control supports filtering data only when the Select method returns a DataSet or DataTable object.

The syntax that is used for the FilterExpression property is a format string–style expression. The filter expression syntax is the same syntax that is accepted by the Expression property. If you add parameters to the FilterParameters collection, you can also include format string placeholders. For example, include "{0}" in the expression to substitute for parameter values. The placeholders are replaced according to the index of the parameter in the FilterParameters collection.

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.

The FilterParameters collection contains the parameters that are evaluated for the placeholders that are found in the FilterExpression property.

The FilterExpression property delegates to the FilterExpression property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.

NoteNote

You should validate any filter parameter value that you receive from the client. 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. 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.

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. The ObjectDataSource control can filter data only when the method that retrieves the data retrieves it as a DataSet or DataTable object. For this reason, the SelectMethod property identifies a business object method that retrieves data as a DataSet.

The code example consists of a TextBox control, a GridView control, the ObjectDataSource control, and a Submit button. By default, the TextBox is populated with the name of one of the Northwind Traders employees. The GridView displays information about the employee that is identified by the name in the TextBox. To retrieve data on another employee, enter the full name of the employee in the TextBox, and then click the Submit button.

The 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. 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.

Security noteSecurity Note

This example has a text box that accepts user input, which is a potential security threat. 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>

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:

  • The EmployeeLogic class, which is a class that encapsulates business logic.

  • 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.

For simplicity, the EmployeeLogic class creates a static set of data, rather than retrieving the data from a data tier. 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. 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;  }
    }    

  }
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.