Parameter Clase

Definición

Ofrece un mecanismo que usan los controles de origen de datos para enlazarse a variables de aplicación, identidades de usuario y opciones, así como a otros datos. Actúa como clase base de 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 se deriva de la ControlParameter clase .

El SelectCommand elemento define la consulta con un parámetro denominado "@Title" donde debe ir el valor de 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>

El código siguiente 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 extender 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 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 parametrizada, una expresión de filtrado o una llamada al método de objeto de negocio que un ASP.NET control de origen de datos usa para seleccionar, filtrar o modificar datos. Los objetos Parameter están contenidos en un objeto ParameterCollection. 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 de origen 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.

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 desee 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 como 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

Parameter()

Inicializa una nueva instancia predeterminada de la clase Parameter.

Parameter(Parameter)

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

Parameter(String)

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

Parameter(String, DbType)

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

Parameter(String, DbType, String)

Inicializa una instancia nueva de la clase Parameter con el nombre y el tipo de base de datos especificados, así como el valor especificado para su propiedad DefaultValue.

Parameter(String, TypeCode)

Inicializa una instancia nueva de la clase Parameter utilizando el tipo y el nombre que se hayan especificado.

Parameter(String, TypeCode, String)

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

Propiedades

ConvertEmptyStringToNull

Obtiene o establece un valor que indica si el valor al que está enlazado el objeto Parameter debe convertirse a null 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 al que está enlazado el parámetro no debe estar inicializado cuando se llame al método Evaluate(HttpContext, Control).

Direction

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

IsTrackingViewState

Obtiene un valor que indica si el objeto Parameter está guardando 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 de parámetro.

ViewState

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

Métodos

Clone()

Devuelve un duplicado de la instancia Parameter actual.

ConvertDbTypeToTypeCode(DbType)

Convierte un valor de DbType en un valor de TypeCode equivalente.

ConvertTypeCodeToDbType(TypeCode)

Convierte un valor de TypeCode en un valor de DbType equivalente.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
Evaluate(HttpContext, Control)

Actualiza y devuelve el valor del objeto Parameter.

GetDatabaseType()

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

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
LoadViewState(Object)

Restaura la vista del origen de datos tal y como se guardó previamente.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnParameterChanged()

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

SaveViewState()

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

SetDirty()

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

ToString()

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

TrackViewState()

Hace que el objeto Parameter realice el seguimiento de los cambios en su estado de vista, de modo que puedan almacenarse en el objeto ViewState del control y mantenerse en todas las solicitudes de la misma página.

Implementaciones de interfaz explícitas

ICloneable.Clone()

Devuelve un duplicado de la instancia Parameter actual.

IStateManager.IsTrackingViewState

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

IStateManager.LoadViewState(Object)

Restaura la vista del origen de datos tal y como se guardó previamente.

IStateManager.SaveViewState()

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

IStateManager.TrackViewState()

Hace que el objeto Parameter realice el seguimiento de los cambios en su estado de vista, de modo que puedan almacenarse en el objeto ViewState del control y mantenerse en todas las solicitudes de la misma página.

Se aplica a

Consulte también