ParameterCollection Classe

Definição

Representa uma coleção de objetos derivados de Parameter e Parameter usados por controles de fonte de dados em cenários de associação de dados avançados.Represents a collection of Parameter and Parameter-derived objects that are used by data source controls in advanced data-binding scenarios.

public ref class ParameterCollection : System::Web::UI::StateManagedCollection
public class ParameterCollection : System.Web.UI.StateManagedCollection
type ParameterCollection = class
    inherit StateManagedCollection
Public Class ParameterCollection
Inherits StateManagedCollection
Herança
ParameterCollection

Exemplos

O exemplo de código a seguir demonstra como usar um AccessDataSource controle e um FormParameter para exibir informações de um banco de dados do Microsoft Access em um GridView controle.The following code example demonstrates how to use an AccessDataSource control and a FormParameter to display information from a Microsoft Access database in a GridView control. O FormParameter objeto é adicionado à SelectParameters coleção usando o Add método.The FormParameter object is added to the SelectParameters collection using the Add method.

Importante

Este exemplo tem uma caixa de texto que aceita a entrada do usuário, que é uma possível ameaça à segurança.This example has a text box that accepts user input, which is a potential security threat. Por padrão, as páginas da Web do ASP.NET validam que a entrada do usuário não inclui elementos de script ou HTML.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Para obter mais informações, consulte Visão geral de explorações de script.For more information, see Script Exploits Overview.

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

void Page_Load(Object sender, EventArgs e){

  // You can add a FormParameter to the AccessDataSource control's
  // SelectParameters collection programmatically.
  AccessDataSource1.SelectParameters.Clear();

  // Security Note: The AccessDataSource uses a FormParameter,
  // Security Note: which does not perform validation of input from the client.
  // Security Note: To validate the value of the FormParameter,
  // Security Note: handle the Selecting event.

  FormParameter formParam = new FormParameter("lastname","LastNameBox");
  formParam.Type=TypeCode.String;
  AccessDataSource1.SelectParameters.Add(formParam);
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:accessdatasource
          id="AccessDataSource1"
          runat="server"
          datasourcemode="DataSet"
          datafile="Northwind.mdb"
          selectcommand="SELECT OrderID,CustomerID,OrderDate,RequiredDate,ShippedDate
                         FROM Orders WHERE EmployeeID =
                         (SELECT EmployeeID FROM Employees WHERE LastName = @lastname)">
      </asp:accessdatasource>

      <br />Enter the name "Davolio" or "King" in the text box and click the button.

      <br />
      <asp:textbox
        id="LastNameBox"
        runat="server" />

      <br />
      <asp:button
        id="Button1"
        runat="server"
        text="Get Records" />

      <br />
      <asp:gridview
          id="GridView1"
          runat="server"
          allowsorting="True"
          datasourceid="AccessDataSource1">
      </asp:gridview>

    </form>
  </body>
</html>
<%@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">

Private Sub Page_Load(sender As Object, e As EventArgs)

  ' You can add a FormParameter to the AccessDataSource control's
  ' SelectParameters collection programmatically.
  AccessDataSource1.SelectParameters.Clear()

  ' Security Note: The AccessDataSource uses a FormParameter,
  ' Security Note: which does not perform validation of input from the client.
  ' Security Note: To validate the value of the FormParameter,
  ' Security Note: handle the Selecting event.

  Dim formParam As New FormParameter("lastname","LastNameBox")
  formParam.Type=TypeCode.String
  AccessDataSource1.SelectParameters.Add(formParam)
End Sub ' Page_Load

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:accessdatasource
          id="AccessDataSource1"
          runat="server"
          datasourcemode="DataSet"
          datafile="Northwind.mdb"
          selectcommand="SELECT OrderID,CustomerID,OrderDate,RequiredDate,ShippedDate
                         FROM Orders WHERE EmployeeID =
                         (SELECT EmployeeID FROM Employees WHERE LastName = @lastname)">
      </asp:accessdatasource>

      <br />Enter the name "Davolio" or "King" in the text box and click the button.

      <br />
      <asp:textbox
        id="LastNameBox"
        runat="server" />

      <br />
      <asp:button
        id="Button1"
        runat="server"
        text="Get Records" />

      <br />
      <asp:gridview
          id="GridView1"
          runat="server"
          allowsorting="True"
          datasourceid="AccessDataSource1">
      </asp:gridview>

    </form>
  </body>
</html>

Comentários

A ParameterCollection classe representa uma coleção de Parameter objetos usados em cenários de ligação de dados avançados com controles de fonte de dados.The ParameterCollection class represents a collection of Parameter objects used in advanced data-binding scenarios with data source controls. Os Parameter objetos são usados para associar os valores contidos por Page variáveis locais, cookies http, variáveis de sessão e valores de outros controles aos controles da fonte de dados ao recuperar, atualizar, excluir e inserir dados.The Parameter objects are used to bind the values contained by local Page variables, HTTP cookies, session variables, and other controls' values to data source controls when retrieving, updating, deleting, and inserting data.

Use a ParameterCollection classe para gerenciar programaticamente um conjunto de Parameter objetos.Use the ParameterCollection class to programmatically manage a set of Parameter objects. Você pode adicionar, inserir e remover Parameter objetos usando os métodos apropriados da ParameterCollection classe.You can add, insert, and remove Parameter objects using the appropriate methods of the ParameterCollection class. Para recuperar Parameter objetos de uma coleção programaticamente, use um dos seguintes métodos:To programmatically retrieve Parameter objects from a collection, use one of following methods:

A Count propriedade especifica o número total de itens na coleção e é usada para determinar o limite superior da coleção.The Count property specifies the total number of items in the collection, and is used to determine the upper bound of the collection. Você pode adicionar e remover itens da coleção usando os Add Insert métodos,, Remove e RemoveAt .You can add and remove items from the collection by using the Add, Insert, Remove, and RemoveAt methods.

Dependendo da implementação e da semântica de um controle de fonte de dados específico, a ordem na qual os parâmetros são armazenados na ParameterCollection coleção pode ser importante.Depending on the implementation and the semantics of a particular data source control, the order in which the parameters are stored in the ParameterCollection collection might be important. Por exemplo, ao usar o SqlDataSource controle como uma fonte de dados ODBC, a ordem dos Parameter objetos na ParameterCollection coleção deve ser igual à ordem dos parâmetros nas consultas SQL parametrizadas que você usa.For example, when using the SqlDataSource control as an ODBC data source, the order of the Parameter objects in the ParameterCollection collection must be the same as the order of the parameters in the parameterized SQL queries you use. No entanto, ao usar o SqlDataSource controle com Microsoft SQL Server, a ordem dos Parameter objetos não é importante.However, when using the SqlDataSource control with Microsoft SQL Server, the order of the Parameter objects are not important.

Importante

Quando você usa controles de fonte de dados, os valores são inseridos em parâmetros de comando sem validação, que é uma possível ameaça à segurança.When you use data source controls, values are inserted into command parameters without validation, which is a potential security threat. Use um evento no controle da fonte de dados para validar valores de parâmetro antes que o comando seja executado.Use an event in the data source control to validate parameter values before the command is executed. Para obter mais informações, consulte Visão geral de explorações de script.For more information, see Script Exploits Overview.

A tabela a seguir lista as diferentes classes de parâmetro e como elas são usadas.The following table lists the different parameter classes and how they are used.

Classe de parâmetroParameter Class DescriçãoDescription
Parameter A classe de parâmetro base.The base parameter class. Use-o para associar a uma variável local ou a qualquer cadeia de caracteres estática usando a DefaultValue propriedade.Use it to bind to a local variable or any static string using the DefaultValue property.
ControlParameter Um parâmetro que pode ser usado para associar a uma propriedade do controle ou um valor de retorno do método.A parameter that can be used to bind to a control's property or method return value.
CookieParameter Um parâmetro que pode ser usado para associar ao valor de um cookie.A parameter that can be used to bind to the value of a cookie.
FormParameter Um parâmetro que pode ser usado para associar a um atributo da página de Web Forms atual.A parameter that can be used to bind to an attribute of the current Web Forms page.
QueryStringParameter Um parâmetro que pode ser usado para associar a um valor passado para uma página de Web Forms em uma cadeia de caracteres de consulta.A parameter that can be used to bind to a value passed to a Web Forms page on a query string.
SessionParameter Um parâmetro que pode ser usado para associar ao valor de uma variável de sessão.A parameter that can be used to bind to the value of a session variable.
ProfileParameter Um parâmetro que pode ser usado para associar ao valor de uma propriedade de perfil ASP.NET.A parameter that can be used to bind to the value of an ASP.NET Profile property.

Construtores

ParameterCollection()

Inicializa a classe para uso por uma instância de classe herdada.Initializes the class for use by an inherited class instance. Esse construtor pode ser chamado apenas por uma classe herdada.This constructor can be called only by an inherited class.

Propriedades

Count

Obtém o número de elementos contidos na coleção StateManagedCollection.Gets the number of elements contained in the StateManagedCollection collection.

(Herdado de StateManagedCollection)
Item[Int32]

Obtém ou define o objeto Parameter no índice especificado na coleção.Gets or sets the Parameter object at the specified index in the collection.

Item[String]

Obtém ou define o objeto Parameter com o nome especificado na coleção.Gets or sets the Parameter object with the specified name in the collection.

Métodos

Add(Parameter)

Acrescenta o objeto Parameter especificado ao final da coleção.Appends the specified Parameter object to the end of the collection.

Add(String, DbType, String)

Cria um objeto Parameter com o nome especificado, tipo de banco de dados e valor padrão e o adiciona ao final da coleção.Creates a Parameter object with the specified name, database type, and default value, and adds it to the end of the collection.

Add(String, String)

Cria um objeto Parameter com o nome especificado e o valor padrão e anexa-o ao final da coleção.Creates a Parameter object with the specified name and default value, and appends it to the end of the collection.

Add(String, TypeCode, String)

Cria um objeto Parameter com o nome especificado, TypeCode e valor padrão e o acrescenta ao final da coleção.Creates a Parameter object with the specified name, TypeCode, and default value, and appends it to the end of the collection.

Clear()

Remove todos os itens da coleção StateManagedCollection.Removes all items from the StateManagedCollection collection.

(Herdado de StateManagedCollection)
Contains(Parameter)

Determina se a coleção ParameterCollection contém um valor específico.Determines whether the ParameterCollection collection contains a specific value.

CopyTo(Array, Int32)

Copia os elementos da coleção StateManagedCollection para uma matriz, começando em um índice de matriz específico.Copies the elements of the StateManagedCollection collection to an array, starting at a particular array index.

(Herdado de StateManagedCollection)
CopyTo(Parameter[], Int32)

Copia um índice especificado de uma matriz de parâmetros para a coleção de parâmetros.Copies a specified index of a parameter array to the parameter collection.

CreateKnownType(Int32)

Cria uma instância de um objeto Parameter padrão.Creates an instance of a default Parameter object.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetEnumerator()

Retorna um iterador que itera por meio da coleção StateManagedCollection.Returns an iterator that iterates through the StateManagedCollection collection.

(Herdado de StateManagedCollection)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetKnownTypes()

Obtém uma matriz de tipos Parameter que a coleção ParameterCollection pode conter.Gets an array of Parameter types that the ParameterCollection collection can contain.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
GetValues(HttpContext, Control)

Obtém uma coleção ordenada de nomes de objetos Parameter e seus valores correspondentes contidos atualmente na coleção.Gets an ordered collection of Parameter object names and their corresponding values currently contained by the collection.

IndexOf(Parameter)

Determina o índice de um objeto Parameter especificado na coleção ParameterCollection.Determines the index of a specified Parameter object in the ParameterCollection collection.

Insert(Int32, Parameter)

Insere o objeto Parameter especificado na coleção ParameterCollection no índice especificado.Inserts the specified Parameter object into the ParameterCollection collection at the specified index.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnClear()

Quando substituído em uma classe derivada, executa o trabalho adicional antes do método Clear() remover todos os itens da coleção.When overridden in a derived class, performs additional work before the Clear() method removes all items from the collection.

(Herdado de StateManagedCollection)
OnClearComplete()

Executa processos personalizados adicionais depois de limpar o conteúdo da coleção.Performs additional custom processes after clearing the contents of the collection.

OnInsert(Int32, Object)

Ocorre antes que o método Insert(Int32, Parameter) seja chamado.Occurs before the Insert(Int32, Parameter) method is called.

OnInsertComplete(Int32, Object)

Ocorre depois que o método Insert(Int32, Parameter) é concluído.Occurs after the Insert(Int32, Parameter) method completes.

OnParametersChanged(EventArgs)

Aciona o evento ParametersChanged.Raises the ParametersChanged event.

OnRemove(Int32, Object)

Quando substituído em uma classe derivada, executa o trabalho adicional antes do método IList.Remove(Object) ou IList.RemoveAt(Int32) remover o item especificado da coleção.When overridden in a derived class, performs additional work before the IList.Remove(Object) or IList.RemoveAt(Int32) method removes the specified item from the collection.

(Herdado de StateManagedCollection)
OnRemoveComplete(Int32, Object)

Ocorre depois que o método Remove(Parameter) é concluído.Occurs after the Remove(Parameter) method completes.

OnValidate(Object)

Executa processos personalizados adicionais ao validar um valor.Performs additional custom processes when validating a value.

Remove(Parameter)

Remove o objeto Parameter especificado da coleção ParameterCollection.Removes the specified Parameter object from the ParameterCollection collection.

RemoveAt(Int32)

Remove o objeto Parameter no índice especificado da coleção ParameterCollection.Removes the Parameter object at the specified index from the ParameterCollection collection.

SetDirty()

Força a coleção StateManagedCollection inteira a ser serializada no estado de exibição.Forces the entire StateManagedCollection collection to be serialized into view state.

(Herdado de StateManagedCollection)
SetDirtyObject(Object)

Marca o objeto Parameter especificado como alterado desde o último carregamento ou salvamento do estado de exibição.Marks the specified Parameter object as having changed since the last load or save from view state.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
UpdateValues(HttpContext, Control)

Itera nos objetos Parameter contidos na coleção e chama o método Evaluate em cada um deles.Iterates through the Parameter objects contained by the collection, and calls the Evaluate method on each one.

Eventos

ParametersChanged

Ocorre quando um ou mais objetos Parameter contidos na coleção muda de estado.Occurs when one or more Parameter objects contained by the collection changes state.

Implantações explícitas de interface

ICollection.Count

Obtém o número de elementos contidos na coleção StateManagedCollection.Gets the number of elements contained in the StateManagedCollection collection.

(Herdado de StateManagedCollection)
ICollection.IsSynchronized

Obtém um valor que indica se a coleção StateManagedCollection é sincronizada (thread-safe).Gets a value indicating whether the StateManagedCollection collection is synchronized (thread safe). Este método retorna false em todos os casos.This method returns false in all cases.

(Herdado de StateManagedCollection)
ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso à coleção StateManagedCollection.Gets an object that can be used to synchronize access to the StateManagedCollection collection. Este método retorna null em todos os casos.This method returns null in all cases.

(Herdado de StateManagedCollection)
IEnumerable.GetEnumerator()

Retorna um iterador que itera por meio da coleção StateManagedCollection.Returns an iterator that iterates through the StateManagedCollection collection.

(Herdado de StateManagedCollection)
IList.Add(Object)

Adiciona um item à coleção StateManagedCollection.Adds an item to the StateManagedCollection collection.

(Herdado de StateManagedCollection)
IList.Clear()

Remove todos os itens da coleção StateManagedCollection.Removes all items from the StateManagedCollection collection.

(Herdado de StateManagedCollection)
IList.Contains(Object)

Determina se a coleção StateManagedCollection contém um valor específico.Determines whether the StateManagedCollection collection contains a specific value.

(Herdado de StateManagedCollection)
IList.IndexOf(Object)

Determina o índice de um item especificado na coleção StateManagedCollection.Determines the index of a specified item in the StateManagedCollection collection.

(Herdado de StateManagedCollection)
IList.Insert(Int32, Object)

Insere um item na coleção StateManagedCollection no índice especificado.Inserts an item into the StateManagedCollection collection at the specified index.

(Herdado de StateManagedCollection)
IList.IsFixedSize

Obtém um valor que indica se a coleção StateManagedCollection tem um tamanho fixo.Gets a value indicating whether the StateManagedCollection collection has a fixed size. Este método retorna false em todos os casos.This method returns false in all cases.

(Herdado de StateManagedCollection)
IList.IsReadOnly

Obtém um valor que indica se a coleção StateManagedCollection é somente leitura.Gets a value indicating whether the StateManagedCollection collection is read-only.

(Herdado de StateManagedCollection)
IList.Item[Int32]

Obtém o elemento IStateManager no índice especificado.Gets the IStateManager element at the specified index.

(Herdado de StateManagedCollection)
IList.Remove(Object)

Remove a primeira ocorrência do objeto especificado da coleção StateManagedCollection.Removes the first occurrence of the specified object from the StateManagedCollection collection.

(Herdado de StateManagedCollection)
IList.RemoveAt(Int32)

Remove o elemento IStateManager no índice especificado.Removes the IStateManager element at the specified index.

(Herdado de StateManagedCollection)
IStateManager.IsTrackingViewState

Obtém um valor que indica se a coleção StateManagedCollection está salvando alterações no estado de exibição.Gets a value indicating whether the StateManagedCollection collection is saving changes to its view state.

(Herdado de StateManagedCollection)
IStateManager.LoadViewState(Object)

Restaura o estado de exibição salvo anteriormente da coleção StateManagedCollection e o itens IStateManager que ele contém.Restores the previously saved view state of the StateManagedCollection collection and the IStateManager items it contains.

(Herdado de StateManagedCollection)
IStateManager.SaveViewState()

Salva as alterações na coleção StateManagedCollection e cada objeto IStateManager que ela contém, desde o momento em que a página foi postada novamente no servidor.Saves the changes to the StateManagedCollection collection and each IStateManager object it contains since the time the page was posted back to the server.

(Herdado de StateManagedCollection)
IStateManager.TrackViewState()

Faz com que a coleção StateManagedCollection e os objetos IStateManager que ela contém controlem as alterações realizadas no estado de exibição, para que elas possam ser mantidas em todas as solicitações para a mesma página.Causes the StateManagedCollection collection and each of the IStateManager objects it contains to track changes to their view state so they can be persisted across requests for the same page.

(Herdado de StateManagedCollection)

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a

Confira também