Share via


Parameter Kelas

Definisi

Menyediakan mekanisme yang digunakan kontrol sumber data untuk mengikat variabel aplikasi, identitas dan pilihan pengguna, dan data lainnya. Berfungsi sebagai kelas dasar untuk semua jenis 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
Warisan
Parameter
Turunan
Penerapan

Contoh

Contoh berikut menunjukkan cara menggunakan nilai kontrol yang DropDownList dipilih dalam klausa Where dari kueri SQL. Contohnya menggunakan ControlParameter kelas , yang berasal dari ControlParameter kelas .

Elemen SelectCommand menentukan kueri dengan parameter bernama "@Title" tempat nilai DropDownList1 harus pergi. Elemen ControlParameter menentukan bahwa tempat penampung "@Title" akan digantikan oleh nilai SelectedValue properti DropDownList1 kontrol. Elemen ControlParameter ditambahkan ke SelectParameters koleksi SqlDataSource kontrol.

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

Contoh berikut seperti yang sebelumnya, tetapi menggunakan kode alih-alih markup. Saat halaman dimuat pertama kali, DropDownList kontrol tidak memiliki nilai yang dipilih, dan DefaultValue properti Parameter objek digunakan.

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

Kode berikut menunjukkan kelas code-behind untuk halaman dalam contoh sebelumnya.

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

Contoh kode berikut menunjukkan cara memperluas Parameter kelas untuk membuat jenis parameter baru yang dapat digunakan oleh kontrol sumber data dan kontrol lain dalam skenario pengikatan data. Kontrol sumber data dapat menggunakan StaticParameter parameter untuk mengikat nilai objek apa pun, biasanya string, yang dideklarasikan pada halaman Formulir Web.

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

Keterangan

Kelas Parameter mewakili parameter dalam kueri SQL berparameter, ekspresi pemfilteran, atau metode objek bisnis yang digunakan kontrol sumber data ASP.NET untuk memilih, memfilter, atau memodifikasi data. Parameter objek terkandung dalam ParameterCollection objek . Parameter Objek dievaluasi pada durasi, untuk mengikat nilai variabel yang diwakilinya ke metode apa pun yang digunakan oleh kontrol sumber data untuk berinteraksi dengan data.

Gunakan kelas yang berasal dari Parameter dengan sumber data dan kontrol terikat data untuk membangun aplikasi data berbasis Web. Kelas parameter ini digunakan oleh kontrol sumber data untuk mengikat jenis nilai tertentu yang ditemukan dalam aplikasi Web ke tempat penampung dalam string kueri SQL, parameter metode objek bisnis, dan banyak lagi. Tabel berikut ini mencantumkan jenis parameter yang disertakan dalam ASP.NET.

ControlParameter Mengikat properti publik apa pun dari kontrol server Web.
FormParameter Mengikat bidang formulir.
SessionParameter Mengikat bidang keadaan sesi.
RouteParameter Mengikat parameter URL rute.
CookieParameter Mengikat bidang cookie.
QueryStringParameter Mengikat parameter string kueri.
ProfileParameter Mengikat bidang profil.

Perluas kelas dasar Parameter saat Anda ingin menerapkan jenis parameter kustom Anda sendiri.

Parameter objek sangat sederhana: mereka memiliki Name properti dan Type , dapat diwakili secara deklaratif, dan dapat melacak status di beberapa permintaan HTTP. Semua parameter mendukung DefaultValue properti, untuk kasus ketika parameter terikat ke nilai, tetapi nilainya dievaluasi pada null durasi.

Saat menggunakan kumpulan Parameter objek dengan kontrol sumber data, urutannya dalam koleksi mungkin penting. Untuk informasi selengkapnya tentang cara parameter digunakan, lihat Menggunakan Parameter dengan Kontrol SqlDataSource dan Menggunakan Parameter dengan Kontrol ObjectDataSource.

Konstruktor

Parameter()

Menginisialisasi instans Parameter default baru kelas.

Parameter(Parameter)

Menginisialisasi instans Parameter baru kelas dengan nilai instans asli yang ditentukan.

Parameter(String)

Menginisialisasi instans Parameter baru kelas, menggunakan nama yang ditentukan.

Parameter(String, DbType)

Menginisialisasi instans Parameter baru kelas, menggunakan nama dan jenis database yang ditentukan.

Parameter(String, DbType, String)

Menginisialisasi instans Parameter baru kelas, menggunakan nama yang ditentukan, jenis database yang ditentukan, dan nilai yang ditentukan untuk propertinya DefaultValue .

Parameter(String, TypeCode)

Menginisialisasi instans Parameter baru kelas, menggunakan nama dan jenis yang ditentukan.

Parameter(String, TypeCode, String)

Menginisialisasi instans Parameter baru kelas, menggunakan nama yang ditentukan, jenis yang ditentukan, dan string yang ditentukan untuk propertinya DefaultValue .

Properti

ConvertEmptyStringToNull

Mendapatkan atau menetapkan nilai yang menunjukkan apakah nilai yang Parameter terikat objek harus dikonversi ke null jika itu adalah Empty.

DbType

Mendapatkan atau mengatur jenis database parameter.

DefaultValue

Menentukan nilai default untuk parameter, jika nilai parameter terikat untuk tidak diinisialisasi saat Evaluate(HttpContext, Control) metode dipanggil.

Direction

Menunjukkan apakah Parameter objek digunakan untuk mengikat nilai ke kontrol, atau kontrol dapat digunakan untuk mengubah nilai.

IsTrackingViewState

Mendapatkan nilai yang menunjukkan apakah Parameter objek menyimpan perubahan pada status tampilannya.

Name

Mendapatkan atau mengatur nama parameter.

Size

Mendapatkan atau mengatur ukuran parameter.

Type

Mendapatkan atau mengatur jenis parameter.

ViewState

Mendapatkan kamus informasi status yang memungkinkan Anda menyimpan dan memulihkan status Parameter tampilan objek di beberapa permintaan untuk halaman yang sama.

Metode

Clone()

Mengembalikan duplikat instans saat ini Parameter .

ConvertDbTypeToTypeCode(DbType)

DbType Mengonversi nilai menjadi nilai yang setaraTypeCode.

ConvertTypeCodeToDbType(TypeCode)

TypeCode Mengonversi nilai menjadi nilai yang setaraDbType.

Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
Evaluate(HttpContext, Control)

Updates dan mengembalikan nilai Parameter objek.

GetDatabaseType()

Mendapatkan nilai yang setara dengan jenis CLR instans DbType saat ini Parameter .

GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetType()

Mendapatkan instans Type saat ini.

(Diperoleh dari Object)
LoadViewState(Object)

Memulihkan status tampilan sumber data yang sebelumnya disimpan.

MemberwiseClone()

Membuat salinan dangkal dari yang saat ini Object.

(Diperoleh dari Object)
OnParameterChanged()

OnParametersChanged(EventArgs) Memanggil metode ParameterCollection koleksi yang berisi Parameter objek .

SaveViewState()

Menyimpan perubahan ke Parameter status tampilan objek sejak halaman diposting kembali ke server.

SetDirty()

Parameter Menandai objek sehingga statusnya akan direkam dalam status tampilan.

ToString()

Mengonversi nilai instans ini ke representasi string yang setara.

TrackViewState()

Parameter Menyebabkan objek melacak perubahan pada status tampilannya sehingga dapat disimpan di objek kontrol ViewState dan bertahan di seluruh permintaan untuk halaman yang sama.

Implementasi Antarmuka Eksplisit

ICloneable.Clone()

Mengembalikan duplikat instans saat ini Parameter .

IStateManager.IsTrackingViewState

Mendapatkan nilai yang menunjukkan apakah Parameter objek menyimpan perubahan pada status tampilannya.

IStateManager.LoadViewState(Object)

Memulihkan status tampilan sumber data yang sebelumnya disimpan.

IStateManager.SaveViewState()

Menyimpan perubahan ke Parameter status tampilan objek sejak halaman diposting kembali ke server.

IStateManager.TrackViewState()

Parameter Menyebabkan objek melacak perubahan pada status tampilannya sehingga dapat disimpan di objek kontrol ViewState dan bertahan di seluruh permintaan untuk halaman yang sama.

Berlaku untuk

Lihat juga