Parameter 类

定义

为数据源控件提供一种绑定到应用程序变量、用户标识和选择以及其他数据的机制。 作为所有 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
继承
Parameter
派生
实现

示例

以下示例演示如何在 SQL 查询的 DropDownList Where 子句中使用控件的选定值。 该示例使用 ControlParameter 派生自 类的 ControlParameter 类。

元素 SelectCommand 使用名为“@Title”的参数定义查询,其值应从 DropDownList1 中转到该参数。 ControlParameter元素指定“@Title”占位符将替换为 控件的 SelectedValue 属性的值DropDownList1。 元素 ControlParameter 将添加到 SelectParameters 控件的 集合中 SqlDataSource

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

以下示例与上一个示例类似,但使用代码而不是标记。 当页面首次加载时,控件 DropDownList 没有选定的值,并且 DefaultValue 使用 对象的 属性 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>

以下代码显示了上一示例中页面的代码隐藏类。

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

下面的代码示例演示如何扩展 Parameter 类以创建可由数据源控件和数据绑定方案中的其他控件使用的新参数类型。 数据源控件可以使用 StaticParameter 参数绑定到在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

注解

Parameter类表示参数化 SQL 查询、筛选表达式或业务对象方法调用中的参数,ASP.NET 数据源控件使用这些调用来选择、筛选或修改数据。 Parameter 对象包含在一个 ParameterCollection 对象中。 Parameter 对象在运行时进行评估,以将它们表示的变量的值绑定到数据源控件用于与数据交互的任何方法。

将派生自 Parameter 的类与数据源和数据绑定控件一起使用来生成基于 Web 的数据应用程序。 数据源控件使用这些参数类将 Web 应用程序中的特定类型的值绑定到 SQL 查询字符串、业务对象方法参数等中的占位符。 下表列出了 ASP.NET 中包含的参数类型。

ControlParameter 绑定 Web 服务器控件的任何公共属性。
FormParameter 绑定窗体域。
SessionParameter 绑定会话状态字段。
RouteParameter 绑定路由 URL 参数。
CookieParameter 绑定 Cookie 字段。
QueryStringParameter 绑定查询字符串参数。
ProfileParameter 绑定配置文件字段。

若要实现自己的自定义参数类型,请扩展基 Parameter 类。

Parameter 对象非常简单:它们具有 NameType 属性,可以声明方式表示,并且可以跨多个 HTTP 请求跟踪状态。 所有参数都支持 DefaultValue 属性,当参数绑定到某个值,但该值在运行时的计算结果为 null 时。

将对象的集合 Parameter 与数据源控件一起使用时,它们在集合中的顺序可能很重要。 有关如何使用参数的详细信息,请参阅 对 SqlDataSource 控件使用参数对 ObjectDataSource 控件使用参数

构造函数

Parameter()

初始化 Parameter 类的新默认实例。

Parameter(Parameter)

使用所指定原始实例的值初始化 Parameter 类的新实例。

Parameter(String)

使用指定的名称初始化 Parameter 类的新实例。

Parameter(String, DbType)

使用指定的名称和数据库类型初始化 Parameter 类的新实例。

Parameter(String, DbType, String)

使用指定的名称、指定的数据库类型及其 Parameter 属性的指定值初始化 DefaultValue 类的新实例。

Parameter(String, TypeCode)

使用指定的名称和类型初始化 Parameter 类的新实例。

Parameter(String, TypeCode, String)

使用 Parameter 类的 DefaultValue 属性的指定名称、指定类型和指定字符串初始化该类的新实例。

属性

ConvertEmptyStringToNull

获取或设置一个值,该值指示在 Parameter 对象绑定到的值为 Empty 时是否应将其转换为 null

DbType

获取或设置参数的数据库类型。

DefaultValue

指定参数的默认值(如果调用 Evaluate(HttpContext, Control) 方法时参数绑定到的值未被初始化)。

Direction

指示 Parameter 对象是否用于将值绑定到控件,或者是否可以使用控件更改值。

IsTrackingViewState

获取一个值,该值指示 Parameter 对象是否保存对其视图状态的更改。

Name

获取或设置参数的名称。

Size

获取或设置参数的大小。

Type

获取或设置参数的类型。

ViewState

获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原 Parameter 对象的视图状态。

方法

Clone()

返回当前 Parameter 实例的副本。

ConvertDbTypeToTypeCode(DbType)

DbType 值转换为等效的 TypeCode 值。

ConvertTypeCodeToDbType(TypeCode)

TypeCode 值转换为等效的 DbType 值。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
Evaluate(HttpContext, Control)

更新并返回 Parameter 对象的值。

GetDatabaseType()

获取与当前 DbType 实例的 CLR 类型等效的 Parameter 值。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
LoadViewState(Object)

将数据源视图还原为保存过的前一视图状态。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
OnParameterChanged()

调用包含 OnParametersChanged(EventArgs) 对象的 ParameterCollection 集合的 Parameter 方法。

SaveViewState()

自页回发到服务器开始,将更改保存到 Parameter 对象的视图状态。

SetDirty()

标记 Parameter 对象,以便在视图状态中记录其状态。

ToString()

将此实例的值转换为其等效的字符串表示形式。

TrackViewState()

使 Parameter 对象跟踪其视图状态更改,以便这些更改可以存储在控件的 ViewState 对象中并在同一页面的不同请求间保留。

显式接口实现

ICloneable.Clone()

返回当前 Parameter 实例的副本。

IStateManager.IsTrackingViewState

获取一个值,该值指示 Parameter 对象是否保存对其视图状态的更改。

IStateManager.LoadViewState(Object)

将数据源视图还原为保存过的前一视图状态。

IStateManager.SaveViewState()

自页回发到服务器开始,将更改保存到 Parameter 对象的视图状态。

IStateManager.TrackViewState()

使 Parameter 对象跟踪其视图状态更改,以便这些更改可以存储在控件的 ViewState 对象中并在同一页面的不同请求间保留。

适用于

另请参阅