GridView.RowCommand Événement
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Se produit lorsqu’un bouton est cliqué dans un GridView contrôle.
public:
event System::Web::UI::WebControls::GridViewCommandEventHandler ^ RowCommand;
public event System.Web.UI.WebControls.GridViewCommandEventHandler RowCommand;
member this.RowCommand : System.Web.UI.WebControls.GridViewCommandEventHandler
Public Custom Event RowCommand As GridViewCommandEventHandler
Type d'événement
Exemples
Un projet de site web Visual Studio avec du code source est disponible pour accompagner cette rubrique : Télécharger.
L’exemple suivant montre comment utiliser l’événement RowCommand pour ajouter le nom d’un client d’un GridView contrôle à un contrôle lorsque le bouton Ajouter d’une ListBox ligne est cliqué.
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ContactsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Add" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row As GridViewRow = ContactsGridView.Rows(index)
' Create a new ListItem object for the contact in the row.
Dim item As New ListItem()
item.Text = Server.HtmlDecode(row.Cells(2).Text) & " " & _
Server.HtmlDecode(row.Cells(3).Text)
' If the contact is not already in the ListBox, add the ListItem
' object to the Items collection of the ListBox control.
If Not ContactsListBox.Items.Contains(item) Then
ContactsListBox.Items.Add(item)
End If
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
L’exemple suivant montre comment utiliser l’événement RowCommand pour mettre à jour le prix d’un produit lorsque le bouton d’une ligne est cliqué. Cet exemple montre comment activer la fonctionnalité de pagination pour le GridView contrôle et définir la CommandArgument propriété du Button contrôle sur l’index de ligne approprié.
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Increase")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ProductsGridView.Rows[index];
// Calculate the new price.
Label listPriceTextBox = (Label)row.FindControl("PriceLabel");
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString();
// Update the row.
ProductsGridView.UpdateRow(index, false);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Increase" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row = ProductsGridView.Rows(index)
' Calculate the new price.
Dim listPriceTextBox = CType(row.FindControl("PriceLabel"), Label)
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString()
' Update the row.
ProductsGridView.UpdateRow(index, False)
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
Remarques
L’événement RowCommand est déclenché lorsqu’un bouton est cliqué dans le GridView contrôle. Cela vous permet de fournir une méthode de gestion des événements qui effectue une routine personnalisée chaque fois que cet événement se produit.
Les boutons d’un GridView contrôle peuvent également appeler certaines des fonctionnalités intégrées du contrôle. Pour effectuer l’une de ces opérations, définissez la CommandName propriété d’un bouton sur l’une des valeurs du tableau suivant.
valeur CommandName |
Description |
|---|---|
Cancel |
Annule une opération de modification et renvoie le contrôle en GridView mode lecture seule. Déclenche l’événement RowCancelingEdit. |
Delete |
Supprime l’enregistrement actif. Déclenche les événements et RowDeleted les RowDeleting événements. |
Edit |
Place l’enregistrement actif en mode édition. Déclenche l’événement RowEditing. |
Page |
Effectue une opération de pagination. Définit la CommandArgument propriété du bouton sur « First », « Last », « Next », « Prev » ou un numéro de page pour spécifier le type d’opération de pagination à effectuer. Déclenche les événements et PageIndexChanged les PageIndexChanging événements. |
Select |
Sélectionne l’enregistrement actif. Déclenche les événements et SelectedIndexChanged les SelectedIndexChanging événements. |
Sort |
Trie le GridView contrôle. Déclenche les événements et Sorted les Sorting événements. |
Update |
Met à jour l’enregistrement actif dans la source de données. Déclenche les événements et RowUpdated les RowUpdating événements. |
Bien que l’événement RowCommand soit déclenché lorsqu’un bouton répertorié dans le tableau précédent est cliqué, il est recommandé d’utiliser les événements répertoriés dans la table pour l’opération.
Un GridViewCommandEventArgs objet est passé à la méthode de gestion des événements, ce qui vous permet de déterminer le nom de la commande et l’argument de commande du bouton cliqué.
Note
Pour déterminer l’index de la ligne qui a déclenché l’événement, utilisez la CommandArgument propriété de l’argument d’événement passé à l’événement. La ButtonField classe remplit automatiquement la CommandArgument propriété avec la valeur d’index appropriée. Pour les autres boutons de commande, vous devez définir manuellement la CommandArgument propriété du bouton de commande. Par exemple, vous pouvez définir la CommandArgument valeur <%# Container.DataItemIndex %> lorsque le GridView contrôle n’a pas de pagination activée.
Pour plus d’informations sur la gestion des événements, consultez Gestion et déclenchement d’événements.