Condividi tramite


Parameter Classe

Definizione

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

public ref class Parameter : ICloneable, System::Web::UI::IStateManager
public class Parameter : ICloneable, System.Web.UI.IStateManager
type Parameter = class
    interface ICloneable
    interface IStateManager
Public Class Parameter
Implements ICloneable, IStateManager
Ereditarietà
Parameter
Derivato
Implementazioni

Esempio

Nell'esempio seguente viene illustrato come usare il valore selezionato di un DropDownList controllo nella clausola Where di una query SQL. Nell'esempio viene utilizzata la ControlParameter classe , che deriva dalla ControlParameter classe .

L'elemento SelectCommand definisce la query con un parametro denominato "@Title" in cui deve passare il valore DropDownList1 . L'elemento ControlParameter specifica che il segnaposto "@Title" verrà sostituito dal valore della SelectedValue proprietà del DropDownList1 controllo. L'elemento ControlParameter viene aggiunto alla SelectParameters raccolta del SqlDataSource controllo .

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <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>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <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'esempio seguente è simile a quello precedente, ma usa codice anziché markup. Quando la pagina viene caricata per la prima volta, il DropDownList controllo non ha alcun valore selezionato e viene utilizzata la DefaultValue proprietà dell'oggetto Parameter .

<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<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>
<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<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>

Il codice seguente illustra la classe code-behind per la pagina nell'esempio 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();
    }
}
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
End Class

Nell'esempio di codice seguente viene illustrato come estendere la Parameter classe per creare un nuovo tipo di parametro che può essere usato dai controlli origine dati e da altri controlli negli scenari di data binding. Un controllo origine dati può utilizzare un StaticParameter parametro per associare al valore di qualsiasi oggetto, in genere una stringa, dichiarata in 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;
    }
  }
}
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

End Namespace ' Samples.AspNet

Commenti

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

Usare classi che derivano da Parameter con l'origine dati e i controlli associati a dati per compilare applicazioni dati basate sul Web. Queste classi di parametri vengono usate dai controlli origine dati per associare tipi specifici di valori presenti nelle applicazioni Web ai segnaposto nelle stringhe di query SQL, ai parametri del metodo oggetto business e altro ancora. Nella tabella seguente sono elencati i tipi di parametro inclusi in ASP.NET.

Tipo di parametro Descrizione
ControlParameter Associa qualsiasi proprietà pubblica di un controllo server Web.
FormParameter Associa un campo modulo.
SessionParameter Associa un campo dello stato sessione.
RouteParameter Associa un parametro URL di route.
CookieParameter Associa un campo cookie.
QueryStringParameter Associa un parametro di stringa di query.
ProfileParameter Associa un campo del profilo.

Estendere la classe di base Parameter quando si desidera implementare i propri tipi di parametri personalizzati.

Parameter gli oggetti sono molto semplici: hanno una Name proprietà e Type possono essere rappresentati in modo dichiarativo e possono tenere traccia dello stato tra più richieste HTTP. Tutti i parametri supportano una DefaultValue proprietà, per i casi in cui un parametro è associato a un valore, ma il valore restituisce null in fase di esecuzione.

Quando si usa una raccolta di Parameter oggetti con un controllo origine dati, l'ordine nella raccolta potrebbe essere rilevante. Per altre informazioni sull'uso dei parametri, vedere Uso dei parametri con il controllo SqlDataSource e Uso dei parametri con il controllo ObjectDataSource.

Costruttori

Nome Descrizione
Parameter()

Inizializza una nuova istanza predefinita della Parameter classe .

Parameter(Parameter)

Inizializza una nuova istanza della Parameter classe con i valori dell'istanza originale specificata.

Parameter(String, DbType, String)

Inizializza una nuova istanza della Parameter classe utilizzando il nome specificato, il tipo di database specificato e il valore specificato per la relativa DefaultValue proprietà.

Parameter(String, DbType)

Inizializza una nuova istanza della Parameter classe utilizzando il nome e il tipo di database specificati.

Parameter(String, TypeCode, String)

Inizializza una nuova istanza della Parameter classe utilizzando il nome specificato, il tipo specificato e la stringa specificata per la relativa DefaultValue proprietà.

Parameter(String, TypeCode)

Inizializza una nuova istanza della Parameter classe utilizzando il nome e il tipo specificati.

Parameter(String)

Inizializza una nuova istanza della Parameter classe utilizzando il nome specificato.

Proprietà

Nome Descrizione
ConvertEmptyStringToNull

Ottiene o imposta un valore che indica se il valore a cui è associato l'oggetto Parameter deve essere convertito null in se è Empty.

DbType

Ottiene o imposta il tipo di database del parametro .

DefaultValue

Specifica un valore predefinito per il parametro , se il valore associato al parametro deve essere non inizializzato quando viene chiamato il Evaluate(HttpContext, Control) metodo .

Direction

Indica se l'oggetto Parameter viene utilizzato per associare un valore a un controllo o se il controllo può essere utilizzato per modificare il valore.

IsTrackingViewState

Ottiene un valore che indica se l'oggetto Parameter sta salvando le modifiche apportate allo stato di visualizzazione.

Name

Ottiene o imposta il nome del parametro.

Size

Ottiene o imposta le dimensioni del parametro.

Type

Ottiene o imposta il tipo del parametro.

ViewState

Ottiene un dizionario di informazioni sullo stato che consente di salvare e ripristinare lo stato di visualizzazione di un Parameter oggetto in più richieste per la stessa pagina.

Metodi

Nome Descrizione
Clone()

Restituisce un duplicato dell'istanza corrente Parameter .

ConvertDbTypeToTypeCode(DbType)

Converte un DbType valore in un valore equivalente TypeCode .

ConvertTypeCodeToDbType(TypeCode)

Converte un TypeCode valore in un valore equivalente DbType .

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Evaluate(HttpContext, Control)

Aggiorna e restituisce il valore dell'oggetto Parameter .

GetDatabaseType()

Ottiene il DbType valore equivalente al tipo CLR dell'istanza corrente Parameter .

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
LoadViewState(Object)

Ripristina lo stato di visualizzazione salvata in precedenza della vista origine dati.

MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
OnParameterChanged()

Chiama il OnParametersChanged(EventArgs) metodo dell'insieme ParameterCollection che contiene l'oggetto Parameter .

SaveViewState()

Salva le modifiche apportate allo Parameter stato di visualizzazione dell'oggetto dal momento in cui la pagina è stata pubblicata nel server.

SetDirty()

Contrassegna l'oggetto Parameter in modo che il relativo stato venga registrato nello stato di visualizzazione.

ToString()

Converte il valore di questa istanza nella rappresentazione di stringa equivalente.

TrackViewState()

Fa in modo che l'oggetto Parameter possa tenere traccia delle modifiche apportate allo stato di visualizzazione in modo che possano essere archiviate nell'oggetto del ViewState controllo e mantenute tra le richieste per la stessa pagina.

Implementazioni dell'interfaccia esplicita

Nome Descrizione
ICloneable.Clone()

Restituisce un duplicato dell'istanza corrente Parameter .

IStateManager.IsTrackingViewState

Ottiene un valore che indica se l'oggetto Parameter sta salvando le modifiche apportate allo stato di visualizzazione.

IStateManager.LoadViewState(Object)

Ripristina lo stato di visualizzazione salvata in precedenza della vista origine dati.

IStateManager.SaveViewState()

Salva le modifiche apportate allo Parameter stato di visualizzazione dell'oggetto dal momento in cui la pagina è stata pubblicata nel server.

IStateManager.TrackViewState()

Fa in modo che l'oggetto Parameter possa tenere traccia delle modifiche apportate allo stato di visualizzazione in modo che possano essere archiviate nell'oggetto del ViewState controllo e mantenute tra le richieste per la stessa pagina.

Si applica a

Vedi anche