Redigeeri

Jagamisviis:


Parameter Class

Definition

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.

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
Inheritance
Parameter
Derived
Implements

Examples

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.

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

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.

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

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

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

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.

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

Remarks

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 null 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.

Constructors

Parameter()

Initializes a new default instance of the Parameter class.

Parameter(Parameter)

Initializes a new instance of the Parameter class with the values of the original, specified instance.

Parameter(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.

Parameter(String, DbType)

Initializes a new instance of the Parameter class, using the specified name and database type.

Parameter(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.

Parameter(String, TypeCode)

Initializes a new instance of the Parameter class, using the specified name and type.

Parameter(String)

Initializes a new instance of the Parameter class, using the specified name.

Properties

ConvertEmptyStringToNull

Gets or sets a value indicating whether the value that the Parameter object is bound to should be converted to null if it is Empty.

DbType

Gets or sets the database type of the parameter.

DefaultValue

Specifies a default value for the parameter, should the value that the parameter is bound to be uninitialized when the Evaluate(HttpContext, Control) method is called.

Direction

Indicates whether the Parameter object is used to bind a value to a control, or the control can be used to change the value.

IsTrackingViewState

Gets a value indicating whether the Parameter object is saving changes to its view state.

Name

Gets or sets the name of the parameter.

Size

Gets or sets the size of the parameter.

Type

Gets or sets the type of the parameter.

ViewState

Gets 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.

Methods

Clone()

Returns a duplicate of the current Parameter instance.

ConvertDbTypeToTypeCode(DbType)

Converts a DbType value to an equivalent TypeCode value.

ConvertTypeCodeToDbType(TypeCode)

Converts a TypeCode value to an equivalent DbType value.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Evaluate(HttpContext, Control)

Updates and returns the value of the Parameter object.

GetDatabaseType()

Gets the DbType value that is equivalent to the CLR type of the current Parameter instance.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
LoadViewState(Object)

Restores the data source view's previously saved view state.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
OnParameterChanged()

Calls the OnParametersChanged(EventArgs) method of the ParameterCollection collection that contains the Parameter object.

SaveViewState()

Saves the changes to the Parameter object's view state since the time the page was posted back to the server.

SetDirty()

Marks the Parameter object so its state will be recorded in view state.

ToString()

Converts the value of this instance to its equivalent string representation.

TrackViewState()

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.

Explicit Interface Implementations

ICloneable.Clone()

Returns a duplicate of the current Parameter instance.

IStateManager.IsTrackingViewState

Gets a value indicating whether the Parameter object is saving changes to its view state.

IStateManager.LoadViewState(Object)

Restores the data source view's previously saved view state.

IStateManager.SaveViewState()

Saves the changes to the Parameter object's view state since the time the page was posted back to the server.

IStateManager.TrackViewState()

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.

Applies to

See also