Questo argomento non è stato ancora valutato - Valuta questo argomento

Classe Parameter

Nota: questa classe è stata introdotta con .NET Framework versione 2.0.

Fornisce un meccanismo utilizzato dai controlli origine dati per l'associazione alle variabili di applicazione, alle identità e scelte dell'utente e ad altri dati. Funge da classe base per tutti i tipi di parametri ASP.NET.

Spazio dei nomi: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)

public class Parameter : ICloneable, IStateManager
public class Parameter implements ICloneable, IStateManager
public class Parameter implements ICloneable, IStateManager

La classe Parameter rappresenta un parametro in una query SQL con parametri, un'espressione di filtro o una chiamata al metodo dell'oggetto business utilizzato dal controllo origine dati ASP.NET per selezionare, filtrare o modificare i dati. Gli oggetti Parameter sono contenuti in un oggetto ParameterCollection. Gli oggetti Parameter vengono valutati in fase di esecuzione per associare i valori delle variabili che rappresentano a un qualsiasi metodo utilizzato da un controllo origine dati per interagire con i dati.

Utilizzare le classi relative al parametro fornite con ASP.NET, incluse ControlParameter, CookieParameter, SessionParameter, ProfileParameter e QueryStringParameter con i controlli origine dati e con associazione a dati per creare applicazioni di dati basate sul Web Queste classi sono utilizzate dai controlli origine dati per associare tipi specifici di valori delle applicazioni Web a segnaposto in stringhe di query SQL, a parametri del metodo dell'oggetto business e altro ancora. Ad esempio la classe ControlParameter è utilizzata per associare qualsiasi proprietà pubblica di un controllo server Web; la classe SessionParameter è utilizzata per associare i valori della sessione utente mentre le classi QueryStringParameter e CookieParameter sono utilizzate per l'associazione ai valori nella classe HttpRequest. Estendere la classe Parameter base quando si desidera implementare tipi di parametri personalizzati.

Gli oggetti Parameter sono molto semplici: dispongono di una proprietà Name e di una proprietà Type, possono essere rappresentati in modo dichiarativo e possono tenere traccia dello stato nelle richieste HTTP multiple. Tutti i parametri supportano una proprietà DefaultValue, nei casi in cui un parametro viene associato a un valore ma il valore restituisce riferimento null (Nothing in Visual Basic) in fase di esecuzione.

Quando si utilizza un insieme di oggetti Parameter con un controllo origine dati, l'ordine nell'insieme può essere rilevante. Per ulteriori informazioni sull'utilizzo dei parametri, vedere Utilizzo dei parametri con il controllo SqlDataSource e Utilizzo dei parametri con il controllo ObjectDataSource.

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare un oggetto Parameter per associare i dati visualizzati in un controllo ListBox al valore selezionato di un controllo DropDownList in uno scenario dichiarativo. L'oggetto ControlParameter viene aggiunto all'insieme SelectParameters del controllo SqlDataSource sul form e corrisponde al testo del segnaposto "@Title" nella proprietà SelectCommand.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <body>
    <form runat="server">

      <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          autopostback="True">
          <asp:listitem selected>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>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
  <BODY>
    <FORM runat="server">

      <p><asp:DropDownList
          id="DropDownList1"
          runat="server"
          AutoPostBack="True">
          <asp:ListItem Selected>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="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          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>

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare un oggetto Parameter per associare i dati visualizzati in un controllo DataGrid al valore selezionato di un controllo DropDownList in uno scenario a livello di codice. Quando si carica inizialmente la pagina, il controllo DropDownList non presenta alcun valore selezionato e viene utilizzata la proprietà DefaultValue dell'oggetto Parameter.

<%@ Page Language="C#" CodeFile="param1acs.aspx.cs" Inherits="param1acs_aspx" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<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>

<%@ Page Language="VJ#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<SCRIPT runat="server">
private void Page_Load(Object sender, System.EventArgs e)
{
    SqlDataSource sqlSource = new SqlDataSource("Data Source=localhost;" 
        + "Integrated Security=SSPI;Initial Catalog=Northwind;",
        "SELECT FirstName, LastName FROM Employees WHERE Country = @country;");

    ControlParameter country = new ControlParameter();
    country.set_Name("country");
    country.set_Type(System.TypeCode.String);
    country.set_ControlID("DropDownList1");
    country.set_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.set_DefaultValue("USA");

    sqlSource.get_SelectParameters().Add(country);

    // Add the SqlDataSource to the page controls collection.
    get_Page().get_Controls().Add(sqlSource);

    DataGrid1.set_DataSource(sqlSource);
    DataGrid1.DataBind();
} //Page_Load
</SCRIPT>

<HTML>
    <BODY>
        <FORM runat="server">

        <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" />

        </FORM>
    </BODY>
</HTML>

Il modulo code-behind riportato di seguito viene utilizzato con la pagina Web Form precedente.

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();
    }
}

Nell'esempio di codice riportato di seguito viene illustrato come estendere la classe Parameter per creare un nuovo tipo di parametro che può essere utilizzato dai controlli origine dati e da altri controlli in scenari di associazione a dati. Un controllo origine dati può utilizzare un parametro StaticParameter da associare al valore di qualsiasi oggetto, in genere una stringa, dichiarato su una pagina Web Form.

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;
    }
  }
}

package Samples.AspNet ;
import System.* ;
import System.ComponentModel.* ;
import System.Web.UI.* ;
import System.Web.UI.WebControls.* ;

public class StaticParameter extends Parameter
{
    public StaticParameter()
    {
    } //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)
    {
        super(name);
        set_DataValue(value);
    } //StaticParameter

    
    // 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)
    {
        super(name, type);
        set_DataValue(value);
    } //StaticParameter

    
    // 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)
    {
        super(original);
        set_DataValue(original.get_DataValue());
    } //StaticParameter


    // 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 Parameter Clone()
    {
        return new StaticParameter(this);
    } //Clone

    
    // The DataValue can be any arbitrary object and is stored in ViewState.
    /** @property 
     */
    public Object get_DataValue()
    {
        return get_ViewState().get_Item("Value");
    } //get_DataValue


    /** @property 
     */
    public void set_DataValue(Object value)
    {
        get_ViewState().set_Item("Value", value);
    } //set_DataValue

    
    // 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.
    /** @property 
     */
    public String get_Value()
    {
        Object o = get_DataValue();

        if (o == null || !(o instanceof String)) {
            return String.Empty;
        }

        return (String)(o);
    } //get_Value


    /** @property 
     */
    public void set_Value(String value)
    {
        set_DataValue(value);
        OnParameterChanged();
    } //set_Value

    
    // The Evaluate method is overridden to return the 
    // DataValue property instead of the DefaultValue.
    protected Object Evaluate(Control control)
    {
        return get_DataValue();
    } //Evaluate
} //StaticParameter

System.Object
  System.Web.UI.WebControls.Parameter
     Classi derivate
I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.

.NET Framework

Supportato in: 2.0
Il documento è risultato utile?
(1500 caratteri rimanenti)

Aggiunte alla community

AGGIUNGI
© 2013 Microsoft. Tutti i diritti riservati.