.NET Framework Class Library QueryStringParameter Class Binds the value of an HTTP request query-string field to a parameter object.

Inheritance Hierarchy
Namespace:
System.Web.UI.WebControls
Assembly:
System.Web (in System.Web.dll)

Syntax
Public Class QueryStringParameter _
Inherits Parameter
public class QueryStringParameter : Parameter
public ref class QueryStringParameter : public Parameter
type QueryStringParameter =
class
inherit Parameter
end
The QueryStringParameter type exposes the following members.

Constructors

Methods

Explicit Interface Implementations

Remarks
You can use the QueryStringParameter class to bind the value of a field that is passed as part of an HTTP request query string to a parameter that is used in a parameterized query or command. The field is retrieved from the QueryString collection. Controls that bind data to the parameter might throw an exception if a QueryStringParameter object is referenced, but no corresponding query-string name/value pair is passed. Similarly, they might display no data if the query-string field name is passed without a corresponding value. To avoid these situations, set the DefaultValue property where appropriate. The QueryStringParameter class provides the QueryStringField property, which identifies the name of the query string value to bind to. It also provides the properties that are inherited from the Parameter class. Important |
|---|
The QueryStringParameter class does not validate the value that is passed; it provides the raw value. However, you can validate the value of a QueryStringParameter object in a data source control. To do so, handle the Selecting, Updating, Inserting, or Deleting event of the data source control and check the parameter value in the event handler. If the value of the parameter does not pass the validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true. |

Examples
The following example shows how to create a QueryStringParameter object to use as a filter when you display data in a GridView control. You add the QueryStringParameter object to the AccessDataSource control's FilterParameters collection. The parameter object binds the value of the query-string field named country to its FilterExpression string. Because no DefaultValue property is specified for the parameter, if no field named country is passed with the query string, the AccessDataSource control throws a NullReferenceException exception. If a field named country is passed but has no value, the GridView control displays no data.
<%@ Page language="VB"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<!-- Use a Query String with country=USA -->
<asp:gridview
id ="GridView1"
runat="server"
datasourceid="MyAccessDataSource" />
<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:accessdatasource
id="MyAccessDataSource"
runat="server"
datafile="Northwind.mdb"
selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
filterexpression="Country = '{0}'">
<filterparameters>
<asp:querystringparameter name="country" type="String" querystringfield="country" />
</filterparameters>
</asp:accessdatasource>
</form>
</body>
</html>
<%@ Page language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<!-- Use a Query String with country=USA -->
<asp:gridview
id ="GridView1"
runat="server"
datasourceid="MyAccessDataSource" />
<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:accessdatasource
id="MyAccessDataSource"
runat="server"
datafile="Northwind.mdb"
selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
filterexpression="Country = '{0}'">
<filterparameters>
<asp:querystringparameter name="country" type="String" querystringfield="country" />
</filterparameters>
</asp:accessdatasource>
</form>
</body>
</html>
The following example shows how to create a QueryStringParameter object to display data from an Access database by using a parameterized SQL query. The AccessDataSource object retrieves records that are then displayed in a GridView control. The GridView control is also editable, and lets users update the status of orders in the Northwind Traders Orders table.
<%@Page Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)
' This method is an example of batch updating using a
' data source control. The method iterates through the rows
' of the GridView, extracts each CheckBox from the row and, if
' the CheckBox is checked, updates data by calling the Update
' method of the data source control, adding required parameters
' to the UpdateParameters collection.
Dim cb As CheckBox
Dim row As GridViewRow
For Each row In GridView1.Rows
cb = CType(row.Cells(0).Controls(1), CheckBox)
If cb.Checked Then
Dim oid As String
oid = CType(row.Cells(1).Text, String)
Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
MyAccessDataSource.UpdateParameters.Add(param1)
Dim param2 As New Parameter("orderid", TypeCode.String, oid)
MyAccessDataSource.UpdateParameters.Add(param2)
MyAccessDataSource.Update()
MyAccessDataSource.UpdateParameters.Clear()
End If
Next
End Sub ' UpdateRecords
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client.
Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->
<asp:SqlDataSource
id="MyAccessDataSource"
runat="server"
ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
<SelectParameters>
<asp:QueryStringParameter Name="empId" QueryStringField="empId" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
id ="GridView1"
runat="server"
DataSourceID="MyAccessDataSource"
AllowPaging="True"
PageSize="10"
AutoGenerateColumns="False">
<columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order" DataField="OrderID" />
<asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
<asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
<asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
</columns>
</asp:GridView>
<asp:Button
id="Button1"
runat="server"
Text="Update the Selected Records As Shipped"
OnClick="UpdateRecords" />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
<%@Page Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
// This method is an example of batch updating using a
// data source control. The method iterates through the rows
// of the GridView, extracts each CheckBox from the row and, if
// the CheckBox is checked, updates data by calling the Update
// method of the data source control, adding required parameters
// to the UpdateParameters collection.
CheckBox cb;
foreach(GridViewRow row in this.GridView1.Rows) {
cb = (CheckBox) row.Cells[0].Controls[1];
if(cb.Checked) {
string oid = (string) row.Cells[1].Text;
MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
MyAccessDataSource.Update();
MyAccessDataSource.UpdateParameters.Clear();
}
}
}
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client.
Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->
<asp:SqlDataSource
id="MyAccessDataSource"
runat="server"
ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
<SelectParameters>
<asp:QueryStringParameter Name="empId" QueryStringField="empId" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
id ="GridView1"
runat="server"
DataSourceID="MyAccessDataSource"
AllowPaging="True"
PageSize="10"
AutoGenerateColumns="False">
<columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order" DataField="OrderID" />
<asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
<asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
<asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
</columns>
</asp:GridView>
<asp:Button
id="Button1"
runat="server"
Text="Update the Selected Records As Shipped"
OnClick="UpdateRecords" />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
<connectionStrings>
<add name="MyPasswordProtectedAccess"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\uncpath\Northwind_PasswordProtected.mdb;Mode=3;Jet OLEDB:Database Password=myPassword;"
providerName="System.Data.OleDb" />
</connectionStrings>

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Bibliothèque de classes .NET Framework QueryStringParameter, classe Lie la valeur d'un champ de chaîne de requête de requête HTTP à un objet Parameter.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web (dans System.Web.dll)

Syntaxe
Public Class QueryStringParameter _
Inherits Parameter
public class QueryStringParameter : Parameter
public ref class QueryStringParameter : public Parameter
type QueryStringParameter =
class
inherit Parameter
end
Le type QueryStringParameter expose les membres suivants.

Constructeurs

Méthodes

Implémentations d'interface explicite

Notes
Vous pouvez utiliser la classe QueryStringParameter pour lier la valeur d'un champ passé dans une chaîne de requête de requête HTTP à un paramètre utilisé dans une requête ou une commande paramétrable. Le champ est récupéré de la collection QueryString. Les contrôles qui lient des données au paramètre peuvent lever une exception si un objet QueryStringParameter est référencé, mais qu'aucune paire nom/valeur de chaîne de requête n'est passée. De même, ils peuvent n'afficher aucune donnée si le nom du champ de chaîne de requête est passé sans valeur correspondante. Définissez la propriété DefaultValue afin d'éviter ce type de situation lorsque cela est approprié. La classe QueryStringParameter fournit la propriété QueryStringField, qui identifie le nom de la valeur de la chaîne de requête à lier. Elle fournit également les propriétés héritées de la classe Parameter. Important |
|---|
La classe QueryStringParameter ne valide en aucun cas la valeur passée. Elle fournit la valeur brute. Toutefois, vous pouvez valider la valeur d'un objet QueryStringParameter dans un contrôle de source de données. Pour ce faire, gérez l'événement Selecting, Updating, Inserting ou Deleting du contrôle de source de données et vérifiez la valeur du paramètre dans le gestionnaire d'événements. Si la valeur du paramètre ne répond pas aux exigences du test de validation, vous pouvez annuler l'opération de données en définissant la propriété Cancel de la classe CancelEventArgs possédant la valeur true. |

Exemples
L'exemple de code suivant montre comment créer un objet QueryStringParameter à utiliser comme filtre pour l'affichage de données dans un contrôle GridView. Vous ajoutez l'objet QueryStringParameter à la collection AccessDataSource du contrôle FilterParameters. L'objet Parameter lie la valeur d'un champ de chaîne de requête nommé country à sa chaîne FilterExpression. Dans la mesure où aucune propriété DefaultValue n'est spécifiée pour le paramètre, si aucun champ nommé country n'est passé dans la chaîne de requête, le contrôle AccessDataSource lève une exception NullReferenceException. Si un champ nommé country est passé mais sans valeur correspondante, le contrôle GridView n'affiche pas de données.
<%@ Page language="VB"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<!-- Use a Query String with country=USA -->
<asp:gridview
id ="GridView1"
runat="server"
datasourceid="MyAccessDataSource" />
<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:accessdatasource
id="MyAccessDataSource"
runat="server"
datafile="Northwind.mdb"
selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
filterexpression="Country = '{0}'">
<filterparameters>
<asp:querystringparameter name="country" type="String" querystringfield="country" />
</filterparameters>
</asp:accessdatasource>
</form>
</body>
</html>
<%@ Page language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<!-- Use a Query String with country=USA -->
<asp:gridview
id ="GridView1"
runat="server"
datasourceid="MyAccessDataSource" />
<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client. -->
<asp:accessdatasource
id="MyAccessDataSource"
runat="server"
datafile="Northwind.mdb"
selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
filterexpression="Country = '{0}'">
<filterparameters>
<asp:querystringparameter name="country" type="String" querystringfield="country" />
</filterparameters>
</asp:accessdatasource>
</form>
</body>
</html>
L'exemple suivant montre comment créer un objet QueryStringParameter pour afficher des données d'une base de données Access à l'aide d'une requête SQL paramétrable. L'objet AccessDataSource récupère des enregistrements qui sont ensuite affichés dans un contrôle GridView. Le contrôle GridView est également modifiable et permet aux utilisateurs de mettre à jour l'état des commandes dans la table Northwind Traders Orders.
<%@Page Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)
' This method is an example of batch updating using a
' data source control. The method iterates through the rows
' of the GridView, extracts each CheckBox from the row and, if
' the CheckBox is checked, updates data by calling the Update
' method of the data source control, adding required parameters
' to the UpdateParameters collection.
Dim cb As CheckBox
Dim row As GridViewRow
For Each row In GridView1.Rows
cb = CType(row.Cells(0).Controls(1), CheckBox)
If cb.Checked Then
Dim oid As String
oid = CType(row.Cells(1).Text, String)
Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
MyAccessDataSource.UpdateParameters.Add(param1)
Dim param2 As New Parameter("orderid", TypeCode.String, oid)
MyAccessDataSource.UpdateParameters.Add(param2)
MyAccessDataSource.Update()
MyAccessDataSource.UpdateParameters.Clear()
End If
Next
End Sub ' UpdateRecords
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client.
Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->
<asp:SqlDataSource
id="MyAccessDataSource"
runat="server"
ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
<SelectParameters>
<asp:QueryStringParameter Name="empId" QueryStringField="empId" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
id ="GridView1"
runat="server"
DataSourceID="MyAccessDataSource"
AllowPaging="True"
PageSize="10"
AutoGenerateColumns="False">
<columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order" DataField="OrderID" />
<asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
<asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
<asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
</columns>
</asp:GridView>
<asp:Button
id="Button1"
runat="server"
Text="Update the Selected Records As Shipped"
OnClick="UpdateRecords" />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
<%@Page Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
// This method is an example of batch updating using a
// data source control. The method iterates through the rows
// of the GridView, extracts each CheckBox from the row and, if
// the CheckBox is checked, updates data by calling the Update
// method of the data source control, adding required parameters
// to the UpdateParameters collection.
CheckBox cb;
foreach(GridViewRow row in this.GridView1.Rows) {
cb = (CheckBox) row.Cells[0].Controls[1];
if(cb.Checked) {
string oid = (string) row.Cells[1].Text;
MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
MyAccessDataSource.Update();
MyAccessDataSource.UpdateParameters.Clear();
}
}
}
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
Security Note: which does not perform validation of input from the client.
Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->
<asp:SqlDataSource
id="MyAccessDataSource"
runat="server"
ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
<SelectParameters>
<asp:QueryStringParameter Name="empId" QueryStringField="empId" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
id ="GridView1"
runat="server"
DataSourceID="MyAccessDataSource"
AllowPaging="True"
PageSize="10"
AutoGenerateColumns="False">
<columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order" DataField="OrderID" />
<asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
<asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
<asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
</columns>
</asp:GridView>
<asp:Button
id="Button1"
runat="server"
Text="Update the Selected Records As Shipped"
OnClick="UpdateRecords" />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
<connectionStrings>
<add name="MyPasswordProtectedAccess"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\uncpath\Northwind_PasswordProtected.mdb;Mode=3;Jet OLEDB:Database Password=myPassword;"
providerName="System.Data.OleDb" />
</connectionStrings>

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
RéférenceAutres ressources
|