Compartir por


Parameter Clase

Definición

Proporciona un mecanismo que los controles de origen de datos usan para enlazar a variables de aplicación, identidades y opciones de usuario y otros datos. Actúa como clase base para todos los tipos de parámetros de 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
Herencia
Parameter
Derivado
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo usar el valor seleccionado de un DropDownList control en la cláusula Where de una consulta SQL. En el ejemplo se usa la ControlParameter clase , que deriva de la ControlParameter clase .

El SelectCommand elemento define la consulta con un parámetro denominado "@Title" donde debe ir el valor.DropDownList1 El ControlParameter elemento especifica que el marcador de posición "@Title" se reemplazará por el valor de la SelectedValue propiedad del DropDownList1 control. El ControlParameter elemento se agrega a la SelectParameters colección del SqlDataSource control .

<!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>

El ejemplo siguiente es como el anterior, pero usa código en lugar de marcado. Cuando la página se carga por primera vez, el DropDownList control no tiene ningún valor seleccionado y se usa la DefaultValue propiedad del Parameter objeto.

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

En el código siguiente se muestra la clase de código subyacente de la página en el ejemplo anterior.

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

En el ejemplo de código siguiente se muestra cómo ampliar la Parameter clase para crear un nuevo tipo de parámetro que pueden usar los controles de origen de datos y otros controles en escenarios de enlace de datos. Un control de origen de datos puede usar un StaticParameter parámetro para enlazar con el valor de cualquier objeto, normalmente una cadena, declarada en una página de Formularios Web Forms.

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

Comentarios

La Parameter clase representa un parámetro en una consulta SQL con parámetros, una expresión de filtrado o una llamada al método de objeto de negocio que usa un control de origen de datos de ASP.NET para seleccionar, filtrar o modificar datos. Parameter los objetos están contenidos en un ParameterCollection objeto . Parameter Los objetos se evalúan en tiempo de ejecución para enlazar los valores de las variables que representan a cualquier método que use un control de origen de datos para interactuar con los datos.

Use clases que derivan de Parameter con controles enlazados a datos y orígenes de datos para compilar aplicaciones de datos basadas en web. Estos controles de origen de datos usan estas clases de parámetros para enlazar tipos específicos de valores que se encuentran en aplicaciones web a marcadores de posición en cadenas de consulta SQL, parámetros de método de objeto de negocio, etc. En la tabla siguiente se enumeran los tipos de parámetro que se incluyen en ASP.NET.

Tipo de parámetro Descripción
ControlParameter Enlaza cualquier propiedad pública de un control de servidor web.
FormParameter Enlaza un campo de formulario.
SessionParameter Enlaza un campo de estado de sesión.
RouteParameter Enlaza un parámetro de dirección URL de ruta.
CookieParameter Enlaza un campo de cookie.
QueryStringParameter Enlaza un parámetro de cadena de consulta.
ProfileParameter Enlaza un campo de perfil.

Extienda la clase base Parameter cuando quiera implementar sus propios tipos de parámetros personalizados.

Parameter los objetos son muy sencillos: tienen una Name propiedad y Type se pueden representar mediante declaración y pueden realizar un seguimiento del estado en varias solicitudes HTTP. Todos los parámetros admiten una DefaultValue propiedad, en los casos en los que un parámetro está enlazado a un valor, pero el valor se evalúa null en tiempo de ejecución.

Cuando se usa una colección de objetos con un control de origen de Parameter datos, su orden en la colección puede ser importante. Para obtener más información sobre cómo se usan los parámetros, vea Using Parameters with the SqlDataSource Control and Using Parameters with the ObjectDataSource Control.

Constructores

Nombre Description
Parameter()

Inicializa una nueva instancia predeterminada de la Parameter clase .

Parameter(Parameter)

Inicializa una nueva instancia de la Parameter clase con los valores de la instancia original especificada.

Parameter(String, DbType, String)

Inicializa una nueva instancia de la Parameter clase utilizando el nombre especificado, el tipo de base de datos especificado y el valor especificado para su DefaultValue propiedad.

Parameter(String, DbType)

Inicializa una nueva instancia de la Parameter clase utilizando el nombre y el tipo de base de datos especificados.

Parameter(String, TypeCode, String)

Inicializa una nueva instancia de la Parameter clase utilizando el nombre especificado, el tipo especificado y la cadena especificada para su DefaultValue propiedad.

Parameter(String, TypeCode)

Inicializa una nueva instancia de la Parameter clase utilizando el nombre y el tipo especificados.

Parameter(String)

Inicializa una nueva instancia de la Parameter clase utilizando el nombre especificado.

Propiedades

Nombre Description
ConvertEmptyStringToNull

Obtiene o establece un valor que indica si el valor al que está enlazado el Parameter objeto se debe convertir null en si es Empty.

DbType

Obtiene o establece el tipo de base de datos del parámetro .

DefaultValue

Especifica un valor predeterminado para el parámetro , si el valor del parámetro está enlazado a no inicializarse cuando se llama al Evaluate(HttpContext, Control) método .

Direction

Indica si el Parameter objeto se usa para enlazar un valor a un control o el control se puede usar para cambiar el valor.

IsTrackingViewState

Obtiene un valor que indica si el Parameter objeto guarda los cambios en su estado de vista.

Name

Obtiene o establece el nombre del parámetro .

Size

Obtiene o establece el tamaño del parámetro .

Type

Obtiene o establece el tipo del parámetro .

ViewState

Obtiene un diccionario de información de estado que permite guardar y restaurar el estado de vista de un Parameter objeto en varias solicitudes para la misma página.

Métodos

Nombre Description
Clone()

Devuelve un duplicado de la instancia actual Parameter .

ConvertDbTypeToTypeCode(DbType)

Convierte un DbType valor en un valor equivalente TypeCode .

ConvertTypeCodeToDbType(TypeCode)

Convierte un TypeCode valor en un valor equivalente DbType .

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
Evaluate(HttpContext, Control)

Actualiza y devuelve el valor del Parameter objeto .

GetDatabaseType()

Obtiene el DbType valor equivalente al tipo CLR de la instancia actual Parameter .

GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
LoadViewState(Object)

Restaura el estado de vista guardado previamente de la vista del origen de datos.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
OnParameterChanged()

Llama al OnParametersChanged(EventArgs) método de la ParameterCollection colección que contiene el Parameter objeto .

SaveViewState()

Guarda los cambios en el Parameter estado de vista del objeto desde el momento en que se devolvió la página al servidor.

SetDirty()

Marca el Parameter objeto para que su estado se registre en estado de vista.

ToString()

Convierte el valor de esta instancia en su representación de cadena equivalente.

TrackViewState()

Hace que el Parameter objeto realice un seguimiento de los cambios en su estado de vista para que se puedan almacenar en el objeto del ViewState control y conservarse en las solicitudes de la misma página.

Implementaciones de interfaz explícitas

Nombre Description
ICloneable.Clone()

Devuelve un duplicado de la instancia actual Parameter .

IStateManager.IsTrackingViewState

Obtiene un valor que indica si el Parameter objeto guarda los cambios en su estado de vista.

IStateManager.LoadViewState(Object)

Restaura el estado de vista guardado previamente de la vista del origen de datos.

IStateManager.SaveViewState()

Guarda los cambios en el Parameter estado de vista del objeto desde el momento en que se devolvió la página al servidor.

IStateManager.TrackViewState()

Hace que el Parameter objeto realice un seguimiento de los cambios en su estado de vista para que se puedan almacenar en el objeto del ViewState control y conservarse en las solicitudes de la misma página.

Se aplica a

Consulte también