ObjectDataSourceFilteringEventArgs Classe

Definizione

Fornisce i dati per l'evento Filtering del controllo ObjectDataSource.Provides data for the Filtering event of the ObjectDataSource control.

public ref class ObjectDataSourceFilteringEventArgs : System::ComponentModel::CancelEventArgs
public class ObjectDataSourceFilteringEventArgs : System.ComponentModel.CancelEventArgs
type ObjectDataSourceFilteringEventArgs = class
    inherit CancelEventArgs
Public Class ObjectDataSourceFilteringEventArgs
Inherits CancelEventArgs
Ereditarietà
ObjectDataSourceFilteringEventArgs

Esempi

In questa sezione sono riportati due esempi di codice.This section contains two code examples. Nel primo esempio di codice viene illustrato come visualizzare i dati filtrati ObjectDataSource utilizzando un controllo per recuperare i dati da un oggetto business di livello intermedio e GridView quindi utilizzando un controllo per visualizzare i risultati.The first code example demonstrates how to display filtered data by using an ObjectDataSource control to retrieve data from a middle-tier business object, and then using a GridView control to display the results. Il secondo esempio di codice fornisce un esempio di un oggetto business di livello intermedio utilizzato dal primo esempio di codice.The second code example provides an example of a middle-tier business object that is used by the first code example.

Nell'esempio di codice riportato di seguito viene illustrato come visualizzare i dati ObjectDataSource filtrati utilizzando un controllo per recuperare i dati da un oggetto business di livello intermedio e quindi utilizzando un GridView controllo per visualizzare i risultati.The following code example demonstrates how to display filtered data by using an ObjectDataSource control to retrieve data from a middle-tier business object, and then using a GridView control to display the results. Il ObjectDataSource controllo consente di filtrare i dati solo quando il metodo che recupera i dati li recupera DataSet come DataTable oggetto o.The ObjectDataSource control can filter data only when the method that retrieves the data retrieves it as a DataSet or DataTable object. Per questo motivo, la SelectMethod proprietà identifica un metodo dell'oggetto business che recupera i dati DataSet come DataTable oggetto o.For this reason, the SelectMethod property identifies a business object method that retrieves data as a DataSet or DataTable object.

L'esempio di codice è costituito da un TextBox controllo, da ObjectDataSource un GridView controllo, dal controllo e da un pulsante Submit .The code example consists of a TextBox control, a GridView control, the ObjectDataSource control, and a Submit button. Per impostazione predefinita, TextBox il controllo viene popolato con il nome di uno dei dipendenti di Northwind Traders.By default, the TextBox control is populated with the name of one of the employees at Northwind Traders. Il GridView controllo Visualizza informazioni sul dipendente identificato dal nome TextBoxin.The GridView control displays information about the employee who is identified by the name in the TextBox. Per recuperare i dati per un altro dipendente, TextBox nel controllo digitare il nome completo del dipendente, quindi fare clic sul pulsante Submit (Invia ).To retrieve data for another employee, in the TextBox control, type the full name of the employee, and then click the Submit button.

La FilterExpression proprietà specifica un'espressione utilizzata per filtrare i dati recuperati dal metodo specificato SelectMethod dalla proprietà.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. USA i segnaposto dei parametri che vengono valutati nei parametri contenuti nella FilterParameters raccolta.It uses parameter placeholders that are evaluated to the parameters that are contained in the FilterParameters collection. In questo esempio, il segnaposto del parametro è racchiuso tra virgolette singole (') perché il tipo del parametro è un tipo stringa che può contenere spazi.In this example, the parameter placeholder is enclosed by single quotation marks (') because the type of the parameter is a string type that might contain spaces. Se il tipo del parametro è numeric o date, le virgolette non sono obbligatorie.If the type of the parameter is numeric or date, quotation marks are not required. La FilterParameters raccolta contiene un parametro, un FormParameter oggetto associato al TextBox controllo.The FilterParameters collection contains one parameter, a FormParameter object that is bound to the TextBox control.

Se nel TextBox controllo non è specificato alcun nome, viene aggiunto un nuovo parametro ParameterValues alla raccolta in modo che la ricerca abbia esito positivo.If no name is specified in the TextBox control, a new parameter is added to the ParameterValues collection so that the search is successful.

Importante

Questo esempio contiene una casella di testo che accetta l'input dell'utente, che rappresenta una potenziale minaccia per la sicurezza.This example contains a text box that accepts user input, which is a potential security threat. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.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>

Nell'esempio di codice riportato di seguito viene fornito un esempio di un oggetto business di livello intermedio utilizzato nell'esempio di codice precedente.The following code example provides an example of a middle-tier business object that the preceding code example uses. L'esempio di codice è costituito da due EmployeeLogic classi NorthwindEmployeedi base: e.The code example consists of two basic classes: EmployeeLogic and NorthwindEmployee. La EmployeeLogic classe incapsula la logica di business e NorthwindEmployee la classe è una classe di modello che contiene solo le funzionalità di base necessarie per caricare e salvare in modo permanente i dati dal livello dati.The EmployeeLogic class encapsulates business logic and the NorthwindEmployee class is a model class that contains only the basic functionality that is required to load and persist data from the data tier. Per semplicità, la EmployeeLogic classe crea un set statico di dati, anziché recuperare i dati da un livello dati.For simplicity, the EmployeeLogic class creates a static set of data, rather than retrieving the data from a data tier. Per un esempio di funzionamento completo, è necessario compilare e utilizzare queste classi con gli esempi di codice Web Form disponibili.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

Commenti

La ObjectDataSourceFilteringEventArgs classe viene utilizzata per passare i dati Filtering al gestore eventi del ObjectDataSource controllo.The ObjectDataSourceFilteringEventArgs class is used to pass data to the Filtering event handler of the ObjectDataSource control. La ParameterValues proprietà fornisce l'accesso ai valori dei parametri di filtro prima che venga eseguita l'operazione di filtro.The ParameterValues property provides access to the filter parameter values before the filtering operation is performed. È possibile annullare il Select metodo impostando la Cancel proprietà di ObjectDataSourceFilteringEventArgs su true.You can cancel the Select method by setting the Cancel property of the ObjectDataSourceFilteringEventArgs to true.

Costruttori

ObjectDataSourceFilteringEventArgs(IOrderedDictionary)

Inizializza una nuova istanza della classe ObjectDataSourceFilteringEventArgs utilizzando l'oggetto specificato.Initializes a new instance of the ObjectDataSourceFilteringEventArgs class by using the specified object.

Proprietà

Cancel

Ottiene o imposta un valore che indica se l'evento debba essere annullato.Gets or sets a value indicating whether the event should be canceled.

(Ereditato da CancelEventArgs)
ParameterValues

Ottiene un'interfaccia IOrderedDictionary che fornisce accesso agli oggetti Parameter della classe ObjectDataSource.Gets an IOrderedDictionary interface that provides access to the Parameter objects of the ObjectDataSource class.

Metodi

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.Serves as the default hash function.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object.

(Ereditato da Object)

Si applica a

Vedi anche