Suggérer une traduction
 
Suggestions d'autres utilisateurs :

progress indicator
Aucune autre suggestion.
Cliquez pour évaluer et commenter
MSDN
MSDN Library
Développement .NET
.NET Framework 4
Espaces de noms System.Web
System.Web.UI.WebControls
Parameter, classe
Réduire tout/Développer tout Réduire tout
Affichage du contenu :  côte à côteAffichage du contenu : côte à côte
.NET Framework Class Library
Parameter Class

Provides a mechanism that data source controls use to bind to application variables, user identities and choices, and other data. Serves as the base class for all ASP.NET parameter types.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
Visual Basic
Public Class Parameter _
    Implements ICloneable, IStateManager
C#
public class Parameter : ICloneable, IStateManager
Visual C++
public ref class Parameter : ICloneable, 
    IStateManager
F#
type Parameter =  
    class
        interface ICloneable
        interface IStateManager
    end

The Parameter type exposes the following members.

  NameDescription
Public methodParameter()()()Initializes a new default instance of the Parameter class.
Protected methodParameter(Parameter)Initializes a new instance of the Parameter class with the values of the original, specified instance.
Public methodParameter(String)Initializes a new instance of the Parameter class, using the specified name.
Public methodParameter(String, DbType)Initializes a new instance of the Parameter class, using the specified name and database type.
Public methodParameter(String, TypeCode)Initializes a new instance of the Parameter class, using the specified name and type.
Public methodParameter(String, DbType, String)Initializes a new instance of the Parameter class, using the specified name, the specified database type, and the specified value for its DefaultValue property.
Public methodParameter(String, TypeCode, String)Initializes a new instance of the Parameter class, using the specified name, the specified type, and the specified string for its DefaultValue property.
Top
  NameDescription
Public propertyConvertEmptyStringToNullGets or sets a value indicating whether the value that the Parameter object is bound to should be converted to nullNothingnullptra null reference (Nothing in Visual Basic) if it is String..::.Empty.
Public propertyDbTypeGets or sets the database type of the parameter.
Public propertyDefaultValueSpecifies a default value for the parameter, should the value that the parameter is bound to be uninitialized when the Evaluate method is called.
Public propertyDirectionIndicates whether the Parameter object is used to bind a value to a control, or the control can be used to change the value.
Protected propertyIsTrackingViewStateGets a value indicating whether the Parameter object is saving changes to its view state.
Public propertyNameGets or sets the name of the parameter.
Public propertySizeGets or sets the size of the parameter.
Public propertyTypeGets or sets the type of the parameter.
Protected propertyViewStateGets a dictionary of state information that allows you to save and restore the view state of a Parameter object across multiple requests for the same page.
Top
  NameDescription
Protected methodCloneReturns a duplicate of the current Parameter instance.
Public methodStatic memberConvertDbTypeToTypeCodeConverts a DbType value to an equivalent TypeCode value.
Public methodStatic memberConvertTypeCodeToDbTypeConverts a TypeCode value to an equivalent DbType value.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodEvaluateUpdates and returns the value of the Parameter object.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetDatabaseTypeGets the DbType value that is equivalent to the CLR type of the current Parameter instance.
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodLoadViewStateRestores the data source view's previously saved view state.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnParameterChangedCalls the OnParametersChanged method of the ParameterCollection collection that contains the Parameter object.
Protected methodSaveViewStateSaves the changes to the Parameter object's view state since the time the page was posted back to the server.
Protected methodSetDirtyMarks the Parameter object so its state will be recorded in view state.
Public methodToStringConverts the value of this instance to its equivalent string representation. (Overrides Object..::.ToString()()().)
Protected methodTrackViewStateCauses the Parameter object to track changes to its view state so they can be stored in the control's ViewState object and persisted across requests for the same page.
Top
  NameDescription
Explicit interface implemetationPrivate methodICloneable..::.CloneReturns a duplicate of the current Parameter instance.
Explicit interface implemetationPrivate propertyIStateManager..::.IsTrackingViewStateInfrastructure. Gets a value indicating whether the Parameter object is saving changes to its view state.
Explicit interface implemetationPrivate methodIStateManager..::.LoadViewStateInfrastructure. Restores the data source view's previously saved view state.
Explicit interface implemetationPrivate methodIStateManager..::.SaveViewStateInfrastructure. Saves the changes to the Parameter object's view state since the time the page was posted back to the server.
Explicit interface implemetationPrivate methodIStateManager..::.TrackViewStateInfrastructure. Causes the Parameter object to track changes to its view state so they can be stored in the control's ViewState object and persisted across requests for the same page.
Top

The Parameter class represents a parameter in a parameterized SQL query, a filtering expression, or a business object method call that an ASP.NET data source control uses to select, filter, or modify data. Parameter objects are contained in a ParameterCollection object. Parameter objects are evaluated at run time, to bind the values of the variables they represent to whatever method is used by a data source control to interact with data.

Use classes that derive from Parameter with data source and data-bound controls to build Web-based data applications. These parameter classes are used by data source controls to bind specific kinds of values found in Web applications to placeholders in SQL query strings, business object method parameters, and more. The following table lists parameter types that are included in ASP.NET.

ControlParameter

Binds any public property of a Web server control.

FormParameter

Binds a form field.

SessionParameter

Binds a session-state field.

RouteParameter

Binds a route URL parameter.

CookieParameter

Binds a cookie field.

QueryStringParameter

Binds a query-string parameter.

ProfileParameter

Binds a profile field.

Extend the base Parameter class when you want to implement your own custom parameter types.

Parameter objects are very simple: they have a Name and a Type property, can be represented declaratively, and can track state across multiple HTTP requests. All parameters support a DefaultValue property, for cases when a parameter is bound to a value, but the value evaluates to nullNothingnullptra null reference (Nothing in Visual Basic) at run time.

When using a collection of Parameter objects with a data source control, their order in the collection might matter. For more information on how parameters are used, see Using Parameters with the SqlDataSource Control and Using Parameters with the ObjectDataSource Control.

The following example shows how to use the selected value of a DropDownList control in the Where clause of a SQL query. The example uses the ControlParameter class, which derives from the ControlParameter class.

The SelectCommand element defines the query with a parameter named "@Title" where the value from DropDownList1 should go. The ControlParameter element specifies that the "@Title" placeholder will be replaced by the value of the SelectedValue property of the DropDownList1 control. The ControlParameter element is added to the SelectParameters collection of the SqlDataSource control.

Visual Basic
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          runat="server"
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          runat="server"
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

    </form>
  </body>
</html>
C#
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          runat="server"
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          runat="server"
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

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

The following example is like the previous one, but uses code instead of markup. When the page loads the first time, the DropDownList control has no selected value, and the DefaultValue property of the Parameter object is used.

Visual Basic
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="param1avb.aspx.vb" Inherits="param1avb_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList
          runat="server"
          AutoPostBack="True"
          id="DropDownList1">
            <asp:ListItem Value="USA">USA</asp:ListItem>
            <asp:ListItem Value="UK">UK</asp:ListItem>
         </asp:DropDownList>

        <asp:DataGrid
          runat="server"
          id="DataGrid1" />    
    </div>
    </form>
</body>
</html>
C#
<%@ Page Language="C#" CodeFile="param1acs.aspx.cs" Inherits="param1acs_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList
          runat="server"
          AutoPostBack="True"
          id="DropDownList1">
            <asp:ListItem Value="USA">USA</asp:ListItem>
            <asp:ListItem Value="UK">UK</asp:ListItem>
         </asp:DropDownList>

        <asp:DataGrid
          runat="server"
          id="DataGrid1" />    
    </div>
    </form>
</body>
</html>

The following code shows the code-behind class for the page in the previous example.

Visual Basic
Partial Class param1avb_aspx
   Inherits System.Web.UI.Page
    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim sqlSource As SqlDataSource

        sqlSource = New SqlDataSource(ConfigurationManager.ConnectionStrings("MyNorthwind").ConnectionString, "SELECT FirstName, LastName FROM Employees WHERE Country = @country;")
        Dim country As New ControlParameter()
        country.Name = "country"
        country.Type = TypeCode.String
        country.ControlID = "DropDownList1"
        country.PropertyName = "SelectedValue"
        ' If the DefaultValue is not set, the DataGrid does not
        ' display anything on the first page load. This is because
        ' on the first page load, the DropDownList has no
        ' selected item, and the ControlParameter evaluates to
        ' String.Empty.
        country.DefaultValue = "USA"
        sqlSource.SelectParameters.Add(country)

        ' Add the SqlDataSource to the page controls collection.
        Page.Controls.Add(sqlSource)


        DataGrid1.DataSource = sqlSource
        DataGrid1.DataBind()

    End Sub 'Page_Load
End Class
C#
public partial class param1acs_aspx : System.Web.UI.Page 
{
    private void Page_Load(object sender, System.EventArgs e)
    {
        SqlDataSource sqlSource = new SqlDataSource(
          ConfigurationManager.ConnectionStrings["MyNorthwind"].ConnectionString,
          "SELECT FirstName, LastName FROM Employees WHERE Country = @country;");

        ControlParameter country = new ControlParameter();
        country.Name = "country";
        country.Type = TypeCode.String;
        country.ControlID = "DropDownList1";
        country.PropertyName = "SelectedValue";

        // If the DefaultValue is not set, the DataGrid does not
        // display anything on the first page load. This is because
        // on the first page load, the DropDownList has no
        // selected item, and the ControlParameter evaluates to
        // String.Empty.
        country.DefaultValue = "USA";

        sqlSource.SelectParameters.Add(country);

        // Add the SqlDataSource to the page controls collection.
        Page.Controls.Add(sqlSource);

        DataGrid1.DataSource = sqlSource;
        DataGrid1.DataBind();
    }
}

The following code example demonstrates how to extend the Parameter class to create a new parameter type that can be used by data source controls and other controls in data-binding scenarios. A data source control can use a StaticParameter parameter to bind to the value of any object, typically a string, declared on a Web Forms page.

Visual Basic
Imports System
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet

<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class StaticParameter
   Inherits Parameter


   Public Sub New()
   End Sub

  ' The StaticParameter(string, object) constructor
  ' initializes the DataValue property and calls the
  ' Parameter(string) constructor to initialize the Name property.
   Public Sub New(name As String, value As Object)
      MyBase.New(name)
      DataValue = value
   End Sub

   ' The StaticParameter(string, TypeCode, object) constructor
   ' initializes the DataValue property and calls the
   ' Parameter(string, TypeCode) constructor to initialize the Name and
   ' Type properties.
   Public Sub New(name As String, type As TypeCode, value As Object)
      MyBase.New(name, type)
      DataValue = value
   End Sub
   ' The StaticParameter copy constructor is provided to ensure that
   ' the state contained in the DataValue property is copied to new
   ' instances of the class.
   Protected Sub New(original As StaticParameter)
      MyBase.New(original)
      DataValue = original.DataValue
   End Sub

   ' The Clone method is overridden to call the
   ' StaticParameter copy constructor, so that the data in
   ' the DataValue property is correctly transferred to the
   ' new instance of the StaticParameter.
   Protected Overrides Function Clone() As Parameter
      Return New StaticParameter(Me)
   End Function

   ' The DataValue can be any arbitrary object and is stored in ViewState.
   Public Property DataValue() As Object
      Get
         Return ViewState("Value")
      End Get
      Set
         ViewState("Value") = value
      End Set
   End Property
   ' The Value property is a type safe convenience property
   ' used when the StaticParameter represents string data.
   ' It gets the string value of the DataValue property, and
   ' sets the DataValue property directly.
   Public Property Value() As String
      Get
         Dim o As Object = DataValue
         If o Is Nothing OrElse Not TypeOf o Is String Then
            Return String.Empty
         End If
         Return CStr(o)
      End Get
      Set
         DataValue = value
         OnParameterChanged()
      End Set
   End Property
   ' The Evaluate method is overridden to return the
   ' DataValue property instead of the DefaultValue.
   Protected Overrides Function Evaluate(context As HttpContext, control As Control) As Object
      If context Is Nothing Then
          Return Nothing
      Else
          Return DataValue
      End If
   End Function
End Class ' StaticParameter

End Namespace ' Samples.AspNet
C#
namespace Samples.AspNet {

  using System;
  using System.ComponentModel;
  using System.Security.Permissions;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;

  [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
  public class StaticParameter : Parameter {

    public StaticParameter() {
    }
    // The StaticParameter(string, object) constructor
    // initializes the DataValue property and calls the
    // Parameter(string) constructor to initialize the Name property.
    public StaticParameter(string name, object value) : base(name) {
      DataValue = value;
    }
    // The StaticParameter(string, TypeCode, object) constructor
    // initializes the DataValue property and calls the
    // Parameter(string, TypeCode) constructor to initialize the Name and
    // Type properties.
    public StaticParameter(string name, TypeCode type, object value) : base(name, type) {
      DataValue = value;
    }
    // The StaticParameter copy constructor is provided to ensure that
    // the state contained in the DataValue property is copied to new
    // instances of the class.
    protected StaticParameter(StaticParameter original) : base(original) {
      DataValue = original.DataValue;
    }

    // The Clone method is overridden to call the
    // StaticParameter copy constructor, so that the data in
    // the DataValue property is correctly transferred to the
    // new instance of the StaticParameter.
    protected override Parameter Clone() {
      return new StaticParameter(this);
    }
    // The DataValue can be any arbitrary object and is stored in ViewState.
    public object DataValue {
      get {
        return ViewState["Value"];
      }
      set {
        ViewState["Value"] = value;
      }
    }
    // The Value property is a type safe convenience property
    // used when the StaticParameter represents string data.
    // It gets the string value of the DataValue property, and
    // sets the DataValue property directly.
    public string Value {
      get {
        object o = DataValue;
        if (o == null || !(o is string))
          return String.Empty;
        return (string)o;
      }
      set {
        DataValue = value;
        OnParameterChanged();
      }
    }

    // The Evaluate method is overridden to return the
    // DataValue property instead of the DefaultValue.
    protected override object Evaluate(HttpContext context, Control control) {

      if (context.Request == null)
          return null;

      return DataValue;
    }
  }
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Bibliothèque de classes .NET Framework
Parameter, classe

Fournit un mécanisme que les contrôles de source de données utilisent pour créer une liaison avec les variables d'application, les identités et les choix utilisateur et d'autres données. Sert de classe de base pour tous les types de paramètres ASP.NET.

Espace de noms :  System.Web.UI.WebControls
Assembly :  System.Web (dans System.Web.dll)
Visual Basic
Public Class Parameter _
    Implements ICloneable, IStateManager
C#
public class Parameter : ICloneable, IStateManager
VisualC++
public ref class Parameter : ICloneable, 
    IStateManager
F#
type Parameter =  
    class
        interface ICloneable
        interface IStateManager
    end

Le type Parameter expose les membres suivants.

  NomDescription
Méthode publiqueParameter()()()Initialise une nouvelle instance par défaut de la classe Parameter.
Méthode protégéeParameter(Parameter)Initialise une nouvelle instance de la classe Parameter avec les valeurs de l'instance originale spécifiée.
Méthode publiqueParameter(String)Initialise une nouvelle instance de la classe Parameter avec le nom spécifié.
Méthode publiqueParameter(String, DbType)Initialise une nouvelle instance de la classe Parameter à l'aide du nom et du type de base de données spécifiés.
Méthode publiqueParameter(String, TypeCode)Initialise une nouvelle instance de la classe Parameter avec le nom et le type spécifiés.
Méthode publiqueParameter(String, DbType, String)Initialise une nouvelle instance de la classe Parameter avec le nom, le type de base de données et la valeur spécifiés pour sa propriété DefaultValue.
Méthode publiqueParameter(String, TypeCode, String)Initialise une nouvelle instance de la classe Parameter, avec le nom, le type et la chaîne spécifiés pour sa propriété DefaultValue.
Début
  NomDescription
Propriété publiqueConvertEmptyStringToNullObtient ou définit une valeur indiquant si la valeur à laquelle l'objet Parameter est lié doit être convertie en nullNothingnullptrune référence null (Nothing en Visual Basic) si elle est String..::.Empty.
Propriété publiqueDbTypeObtient ou définit le type de base de données du paramètre.
Propriété publiqueDefaultValueSpécifie une valeur par défaut pour le paramètre, à condition que la valeur à laquelle le paramètre est lié à ne soit pas initialisée lorsque la méthode Evaluate est appelée.
Propriété publiqueDirectionIndique si l'objet Parameter est utilisé pour lier une valeur à un contrôle ou si le contrôle peut être utilisé pour modifier la valeur.
Propriété protégéeIsTrackingViewStateObtient une valeur indiquant si l'objet Parameter enregistre les modifications apportées à son état d'affichage.
Propriété publiqueNameObtient ou définit le nom du paramètre.
Propriété publiqueSizeObtient ou définit la taille du paramètre.
Propriété publiqueTypeObtient ou définit le type du paramètre.
Propriété protégéeViewStateObtient un dictionnaire d'informations d'état qui vous permet d'enregistrer et de restaurer l'état d'affichage d'un objet Parameter entre plusieurs demandes de la même page.
Début
  NomDescription
Méthode protégéeCloneRetourne un doublon de l'instance de Parameter actuelle.
Méthode publiqueMembre statiqueConvertDbTypeToTypeCodeConvertit une valeur DbType en valeur TypeCode équivalente.
Méthode publiqueMembre statiqueConvertTypeCodeToDbTypeConvertit une valeur TypeCode en valeur DbType équivalente.
Méthode publiqueEquals(Object)Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.)
Méthode protégéeEvaluateMet à jour et retourne la valeur de l'objet Parameter.
Méthode protégéeFinalizeAutorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)
Méthode publiqueGetDatabaseTypeObtient la valeur DbType qui est équivalente au type CLR de l'instance Parameter actuelle.
Méthode publiqueGetHashCodeSert de fonction de hachage pour un type particulier. (Hérité de Object.)
Méthode publiqueGetTypeObtient le Type de l'instance actuelle. (Hérité de Object.)
Méthode protégéeLoadViewStateRestaure l'état d'affichage enregistré précédemment pour la vue de source de données.
Méthode protégéeMemberwiseCloneCrée une copie superficielle de l'objet Object actif. (Hérité de Object.)
Méthode protégéeOnParameterChangedAppelle la méthode OnParametersChanged de la collection ParameterCollection qui contient l'objet Parameter.
Méthode protégéeSaveViewStateEnregistre les modifications apportées à l'état d'affichage de l'objet Parameter depuis la publication de la page sur le serveur.
Méthode protégéeSetDirtyMarque l'objet Parameter afin que son état soit enregistré dans l'état d'affichage.
Méthode publiqueToStringConvertit la valeur de cette instance en sa représentation sous forme de chaîne équivalente. (Substitue Object..::.ToString()()().)
Méthode protégéeTrackViewStateAinsi, l'objet Parameter effectue le suivi des modifications de son état d'affichage afin qu'elles puissent être stockées dans l'objet ViewState du contrôle et être persistantes entre les demandes de la même page.
Début
  NomDescription
Implémentation d'interface expliciteMéthode privéeICloneable..::.CloneRetourne un doublon de l'instance de Parameter actuelle.
Implémentation d'interface explicitePropriété privéeIStateManager..::.IsTrackingViewStateInfrastructure. Obtient une valeur indiquant si l'objet Parameter enregistre les modifications apportées à son état d'affichage.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.LoadViewStateInfrastructure. Restaure l'état d'affichage enregistré précédemment pour la vue de source de données.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.SaveViewStateInfrastructure. Enregistre les modifications apportées à l'état d'affichage de l'objet Parameter depuis la publication de la page sur le serveur.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.TrackViewStateInfrastructure. Ainsi, l'objet Parameter effectue le suivi des modifications de son état d'affichage afin qu'elles puissent être stockées dans l'objet ViewState du contrôle et être persistantes entre les demandes de la même page.
Début

La classe Parameter représente un paramètre dans une requête SQL paramétrée, une expression de filtrage ou un appel de méthode d'objet métier utilisé par un contrôle de source de données ASP.NET pour sélectionner, filtrer ou modifier des données. Les objets Parameter sont contenus dans un objet ParameterCollection. Les objets Parameter sont évalués au moment de l'exécution, pour lier les valeurs des variables qu'ils représentent à n'importe quelle méthode utilisée par un contrôle de source de données pour interagir avec les données.

Utilisez les classes qui dérivent de Parameter avec les contrôles de source de données et liés aux données pour créer des applications de données Web. Ces classes de paramètres sont utilisées par les contrôles de source de données pour lier les types spécifiques de valeurs présents dans les applications Web aux espaces réservés dans les chaînes de requête SQL, aux paramètres de la méthode de l'objet métier, etc. Le tableau suivant répertorie les types de paramètres inclus dans ASP.NET.

ControlParameter

Lie toute propriété publique d'un contrôle serveur Web.

FormParameter

Lie un champ de formulaire.

SessionParameter

Lie un champ d'état de session.

RouteParameter

Lie un paramètre d'URL de routage.

CookieParameter

Lie un champ de cookie.

QueryStringParameter

Lie un paramètre de chaîne de requête.

ProfileParameter

Lie un champ de profil.

Étendez la classe Parameter de base lorsque vous souhaitez implémenter vos propres types de paramètres personnalisés.

Les objets Parameter sont très simples : ils ont un Name et une propriété Type, ils peuvent être représentés de manière déclarative et peuvent effectuer un suivi de l'état à travers plusieurs requêtes HTTP. Tous les paramètres prennent en charge une propriété DefaultValue, dans les cas où un paramètre est lié à une valeur, mais la valeur est nullNothingnullptrune référence null (Nothing en Visual Basic) au moment de l'exécution.

Lors de l'utilisation d'une collection d'objets Parameter avec un contrôle de source de données, leur ordre dans la collection peut avoir une importance. Pour plus d'informations sur la façon dont les paramètres sont utilisés, consultez Utilisation de paramètres avec le contrôle SqlDataSource et Utilisation de paramètres avec le contrôle ObjectDataSource.

L'exemple suivant montre comment utiliser la valeur sélectionnée d'un contrôle DropDownList dans la clause Where d'une requête SQL. L'exemple utilise la classe ControlParameter dérivée de la classe ControlParameter.

L'élément SelectCommand définit la requête avec un paramètre nommé "@Title" où la valeur de DropDownList1 doit être placée. L'élément ControlParameter spécifie que l'espace réservé "@Title" sera remplacé par la valeur de la propriété SelectedValue du contrôle DropDownList1. L'élément ControlParameter est ajouté à la collection SelectParameters du contrôle SqlDataSource.

Visual Basic
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          runat="server"
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          runat="server"
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

    </form>
  </body>
</html>
C#
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          autopostback="True">
          <asp:listitem selected="True">Sales Representative</asp:listitem>
          <asp:listitem>Sales Manager</asp:listitem>
          <asp:listitem>Vice President, Sales</asp:listitem>
      </asp:dropdownlist></p>

      <asp:sqldatasource
          id="SqlDataSource1"
          runat="server"
          connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
          selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
          <selectparameters>
              <asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
          </selectparameters>
      </asp:sqldatasource>

      <p><asp:listbox
          id="ListBox1"
          runat="server"
          datasourceid="SqlDataSource1"
          datatextfield="LastName">
      </asp:listbox></p>

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

L'exemple suivant est semblable au précédent, mais il utilise le code au lieu du balisage. Lorsque la page se charge pour la première fois, le contrôle DropDownList n'a aucune valeur sélectionnée et la propriété DefaultValue de l'objet Parameter est utilisée.

Visual Basic
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="param1avb.aspx.vb" Inherits="param1avb_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList
          runat="server"
          AutoPostBack="True"
          id="DropDownList1">
            <asp:ListItem Value="USA">USA</asp:ListItem>
            <asp:ListItem Value="UK">UK</asp:ListItem>
         </asp:DropDownList>

        <asp:DataGrid
          runat="server"
          id="DataGrid1" />    
    </div>
    </form>
</body>
</html>
C#
<%@ Page Language="C#" CodeFile="param1acs.aspx.cs" Inherits="param1acs_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList
          runat="server"
          AutoPostBack="True"
          id="DropDownList1">
            <asp:ListItem Value="USA">USA</asp:ListItem>
            <asp:ListItem Value="UK">UK</asp:ListItem>
         </asp:DropDownList>

        <asp:DataGrid
          runat="server"
          id="DataGrid1" />    
    </div>
    </form>
</body>
</html>

Le code suivant présente la classe code-behind pour la page dans l'exemple précédent.

Visual Basic
Partial Class param1avb_aspx
   Inherits System.Web.UI.Page
    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim sqlSource As SqlDataSource

        sqlSource = New SqlDataSource(ConfigurationManager.ConnectionStrings("MyNorthwind").ConnectionString, "SELECT FirstName, LastName FROM Employees WHERE Country = @country;")
        Dim country As New ControlParameter()
        country.Name = "country"
        country.Type = TypeCode.String
        country.ControlID = "DropDownList1"
        country.PropertyName = "SelectedValue"
        ' If the DefaultValue is not set, the DataGrid does not
        ' display anything on the first page load. This is because
        ' on the first page load, the DropDownList has no
        ' selected item, and the ControlParameter evaluates to
        ' String.Empty.
        country.DefaultValue = "USA"
        sqlSource.SelectParameters.Add(country)

        ' Add the SqlDataSource to the page controls collection.
        Page.Controls.Add(sqlSource)


        DataGrid1.DataSource = sqlSource
        DataGrid1.DataBind()

    End Sub 'Page_Load
End Class
C#
public partial class param1acs_aspx : System.Web.UI.Page 
{
    private void Page_Load(object sender, System.EventArgs e)
    {
        SqlDataSource sqlSource = new SqlDataSource(
          ConfigurationManager.ConnectionStrings["MyNorthwind"].ConnectionString,
          "SELECT FirstName, LastName FROM Employees WHERE Country = @country;");

        ControlParameter country = new ControlParameter();
        country.Name = "country";
        country.Type = TypeCode.String;
        country.ControlID = "DropDownList1";
        country.PropertyName = "SelectedValue";

        // If the DefaultValue is not set, the DataGrid does not
        // display anything on the first page load. This is because
        // on the first page load, the DropDownList has no
        // selected item, and the ControlParameter evaluates to
        // String.Empty.
        country.DefaultValue = "USA";

        sqlSource.SelectParameters.Add(country);

        // Add the SqlDataSource to the page controls collection.
        Page.Controls.Add(sqlSource);

        DataGrid1.DataSource = sqlSource;
        DataGrid1.DataBind();
    }
}

L'exemple de code suivant montre comment étendre la classe Parameter pour créer un nouveau type de paramètre qui peut être utilisé par les contrôles de source de données et d'autres contrôles dans les scénarios de liaison de données. Un contrôle de source de données peut utiliser un paramètre StaticParameter pour créer une liaison avec la valeur de tout objet, en général une chaîne, déclarée sur une page Web Forms.

Visual Basic
Imports System
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet

<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class StaticParameter
   Inherits Parameter


   Public Sub New()
   End Sub

  ' The StaticParameter(string, object) constructor
  ' initializes the DataValue property and calls the
  ' Parameter(string) constructor to initialize the Name property.
   Public Sub New(name As String, value As Object)
      MyBase.New(name)
      DataValue = value
   End Sub

   ' The StaticParameter(string, TypeCode, object) constructor
   ' initializes the DataValue property and calls the
   ' Parameter(string, TypeCode) constructor to initialize the Name and
   ' Type properties.
   Public Sub New(name As String, type As TypeCode, value As Object)
      MyBase.New(name, type)
      DataValue = value
   End Sub
   ' The StaticParameter copy constructor is provided to ensure that
   ' the state contained in the DataValue property is copied to new
   ' instances of the class.
   Protected Sub New(original As StaticParameter)
      MyBase.New(original)
      DataValue = original.DataValue
   End Sub

   ' The Clone method is overridden to call the
   ' StaticParameter copy constructor, so that the data in
   ' the DataValue property is correctly transferred to the
   ' new instance of the StaticParameter.
   Protected Overrides Function Clone() As Parameter
      Return New StaticParameter(Me)
   End Function

   ' The DataValue can be any arbitrary object and is stored in ViewState.
   Public Property DataValue() As Object
      Get
         Return ViewState("Value")
      End Get
      Set
         ViewState("Value") = value
      End Set
   End Property
   ' The Value property is a type safe convenience property
   ' used when the StaticParameter represents string data.
   ' It gets the string value of the DataValue property, and
   ' sets the DataValue property directly.
   Public Property Value() As String
      Get
         Dim o As Object = DataValue
         If o Is Nothing OrElse Not TypeOf o Is String Then
            Return String.Empty
         End If
         Return CStr(o)
      End Get
      Set
         DataValue = value
         OnParameterChanged()
      End Set
   End Property
   ' The Evaluate method is overridden to return the
   ' DataValue property instead of the DefaultValue.
   Protected Overrides Function Evaluate(context As HttpContext, control As Control) As Object
      If context Is Nothing Then
          Return Nothing
      Else
          Return DataValue
      End If
   End Function
End Class ' StaticParameter

End Namespace ' Samples.AspNet
C#
namespace Samples.AspNet {

  using System;
  using System.ComponentModel;
  using System.Security.Permissions;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;

  [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
  public class StaticParameter : Parameter {

    public StaticParameter() {
    }
    // The StaticParameter(string, object) constructor
    // initializes the DataValue property and calls the
    // Parameter(string) constructor to initialize the Name property.
    public StaticParameter(string name, object value) : base(name) {
      DataValue = value;
    }
    // The StaticParameter(string, TypeCode, object) constructor
    // initializes the DataValue property and calls the
    // Parameter(string, TypeCode) constructor to initialize the Name and
    // Type properties.
    public StaticParameter(string name, TypeCode type, object value) : base(name, type) {
      DataValue = value;
    }
    // The StaticParameter copy constructor is provided to ensure that
    // the state contained in the DataValue property is copied to new
    // instances of the class.
    protected StaticParameter(StaticParameter original) : base(original) {
      DataValue = original.DataValue;
    }

    // The Clone method is overridden to call the
    // StaticParameter copy constructor, so that the data in
    // the DataValue property is correctly transferred to the
    // new instance of the StaticParameter.
    protected override Parameter Clone() {
      return new StaticParameter(this);
    }
    // The DataValue can be any arbitrary object and is stored in ViewState.
    public object DataValue {
      get {
        return ViewState["Value"];
      }
      set {
        ViewState["Value"] = value;
      }
    }
    // The Value property is a type safe convenience property
    // used when the StaticParameter represents string data.
    // It gets the string value of the DataValue property, and
    // sets the DataValue property directly.
    public string Value {
      get {
        object o = DataValue;
        if (o == null || !(o is string))
          return String.Empty;
        return (string)o;
      }
      set {
        DataValue = value;
        OnParameterChanged();
      }
    }

    // The Evaluate method is overridden to return the
    // DataValue property instead of the DefaultValue.
    protected override object Evaluate(HttpContext context, Control control) {

      if (context.Request == null)
          return null;

      return DataValue;
    }
  }
}

.NET Framework

Pris en charge dans : 4, 3.5, 3.0, 2.0

Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2

Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Tous les membres static (Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Contenu de la communauté   Qu'est-ce que le Contenu de la communauté ?
Ajouter du contenu RSS  Annotations
Processing
© 2012 Microsoft. Tous droits réservés. Conditions d'utilisation | Marques | Confidentialité
Page view tracker