ListView.ItemCommand Evento
Definição
public:
event EventHandler<System::Web::UI::WebControls::ListViewCommandEventArgs ^> ^ ItemCommand;
public event EventHandler<System.Web.UI.WebControls.ListViewCommandEventArgs> ItemCommand;
member this.ItemCommand : EventHandler<System.Web.UI.WebControls.ListViewCommandEventArgs>
Public Custom Event ItemCommand As EventHandler(Of ListViewCommandEventArgs)
Tipo de evento
Exemplos
O exemplo a seguir mostra como criar um ItemCommand manipulador de eventos.The following example shows how to create an ItemCommand event handler.
<%@ 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">
protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "AddToList"))
{
// Verify that the employee ID is not already in the list. If not, add the
// employee to the list.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
string employeeID =
EmployeesListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
if (SelectedEmployeesListBox.Items.FindByValue(employeeID) == null)
{
ListItem item = new ListItem(e.CommandArgument.ToString(), employeeID);
SelectedEmployeesListBox.Items.Add(item);
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Employee List</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ListView runat="server"
ID="EmployeesListView"
OnItemCommand="EmployeesListView_OnItemCommand"
DataSourceID="EmployeesDataSource"
DataKeyNames="EmployeeID">
<LayoutTemplate>
<table runat="server" id="tblEmployees"
cellspacing="0" cellpadding="1" width="440px" border="1">
<tr id="itemPlaceholder" runat="server"></tr>
</table>
<asp:DataPager ID="EmployeesDataPager" runat="server" PageSize="10">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label runat="server" ID="NameLabel"
Text='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
</td>
<td style="width:80px">
<asp:LinkButton runat="server"
ID="SelectEmployeeButton"
Text="Add To List"
CommandName="AddToList"
CommandArgument='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<br /><br />
<b>Selected Employees:</b><br />
<asp:ListBox runat="server" ID="SelectedEmployeesListBox" Rows="10" Width="300px" />
<!-- 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="EmployeesDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT [EmployeeID], [FirstName], [LastName]
FROM HumanResources.vEmployee
ORDER BY [LastName], [FirstName], [EmployeeID]">
</asp:SqlDataSource>
</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">
Protected Sub EmployeesListView_OnItemCommand(ByVal sender As Object, _
ByVal e As ListViewCommandEventArgs)
If String.Equals(e.CommandName, "AddToList") Then
' Verify that the employee ID is not already in the list. If not, add the
' employee to the list.
Dim dataItem As ListViewDataItem = CType(e.Item, ListViewDataItem)
Dim employeeID As String = _
EmployeesListView.DataKeys(dataItem.DisplayIndex).Value.ToString()
If SelectedEmployeesListBox.Items.FindByValue(employeeID) Is Nothing Then
Dim item As ListItem = _
New ListItem(e.CommandArgument.ToString(), employeeID)
SelectedEmployeesListBox.Items.Add(item)
End If
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<title>Employee List</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ListView runat="server"
ID="EmployeesListView"
OnItemCommand="EmployeesListView_OnItemCommand"
DataSourceID="EmployeesDataSource"
DataKeyNames="EmployeeID">
<LayoutTemplate>
<table runat="server" id="tblEmployees"
cellspacing="0" cellpadding="1" width="440px" border="1">
<tr id="itemPlaceholder" runat="server"></tr>
</table>
<asp:DataPager ID="EmployeesDataPager" runat="server" PageSize="10">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label runat="server" ID="NameLabel"
Text='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
</td>
<td style="width:80px">
<asp:LinkButton runat="server"
ID="SelectEmployeeButton"
Text="Add To List"
CommandName="AddToList"
CommandArgument='<%#Eval("LastName") & ", " & Eval("FirstName") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<br /><br />
<b>Selected Employees:</b><br />
<asp:ListBox runat="server" ID="SelectedEmployeesListBox" Rows="10" Width="300px" />
<!-- 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="EmployeesDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
SelectCommand="SELECT [EmployeeID], [FirstName], [LastName]
FROM HumanResources.vEmployee
ORDER BY [LastName], [FirstName], [EmployeeID]">
</asp:SqlDataSource>
</form>
</body>
</html>
Comentários
O ItemCommand evento é gerado quando um botão no ListView controle é clicado.The ItemCommand event is raised when a button in the ListView control is clicked. Isso permite que você execute uma rotina personalizada sempre que esse evento ocorrer.This enables you to perform a custom routine whenever this event occurs.
Os botões em um ListView controle também podem invocar a funcionalidade interna do controle.Buttons in a ListView control can also invoke built-in functionality of the control. A tabela a seguir lista os valores que você pode usar com a CommandName propriedade de um botão para invocar a funcionalidade interna.The following table lists values that you can use with the CommandName property of a button in order to invoke built-in functionality.
| Valor de CommandNameCommandName value | DescriçãoDescription |
|---|---|
| Cancela"Cancel" | Cancela uma operação de edição ou inserção.Cancels an edit or insert operation. Aciona o evento ItemCanceling.Raises the ItemCanceling event. |
| Apagar"Delete" | Exclui o registro atual da fonte de dados.Deletes the current record from the data source. Gera os ItemDeleted ItemDeleting eventos e.Raises the ItemDeleted and ItemDeleting events. |
| "Selecionar""Select" | Define a SelectedIndex propriedade como o DisplayIndex valor da propriedade para o item.Sets the SelectedIndex property to the DisplayIndex property value for the item. Renderiza o SelectedItemTemplate modelo para o item.Renders the SelectedItemTemplate template for the item. Gera os SelectedIndexChanging SelectedIndexChanged eventos e.Raises the SelectedIndexChanging and SelectedIndexChanged events. |
| Editar"Edit" | Coloca o item no modo de edição.Puts the item in edit mode. Renderiza o EditItemTemplate modelo para o item.Renders the EditItemTemplate template for the item. Aciona o evento ItemEditing.Raises the ItemEditing event. |
| Inserido"Insert" | Insere os valores associados do InsertItemTemplate modelo na fonte de dados.Inserts the bound values from the InsertItemTemplate template into the data source. Gera os ItemInserting ItemInserted eventos e.Raises the ItemInserting and ItemInserted events. |
| Cumulativo"Update" | Atualiza o registro atual na fonte de dados com os valores associados do EditItemTemplate modelo.Updates the current record in the data source with the bound values from the EditItemTemplate template. Gera os ItemUpdating ItemUpdated eventos e.Raises the ItemUpdating and ItemUpdated events. |
| Organizar"Sort" | Classifica as colunas listadas na CommandArgument Propriedade do botão.Sorts the columns listed in the CommandArgument property of the button. Gera os Sorting Sorted eventos e.Raises the Sorting and Sorted events. |
O ItemCommand evento também é gerado quando um botão listado na tabela anterior é clicado.The ItemCommand event is also raised when a button that is listed in the previous table is clicked. No entanto, é recomendável que você use os eventos listados na tabela.However, it is recommended that you use the events listed in the table. O ItemCommand evento é geralmente usado para lidar com operações personalizadas.The ItemCommand event is usually used to handle custom operations.
Um ListViewCommandEventArgs objeto é passado para o manipulador de eventos, que permite que você determine o nome do comando e o argumento de comando do botão que foi clicado.A ListViewCommandEventArgs object is passed to the event handler, which enables you to determine the command name and command argument of the button that was clicked. Para determinar o nome do comando, use a CommandEventArgs.CommandName propriedade.To determine the command name, use the CommandEventArgs.CommandName property. Para determinar o argumento de comando, use a CommandEventArgs.CommandArgument propriedade.To determine the command argument, use the CommandEventArgs.CommandArgument property. Para acessar o controle que disparou o evento, use a ListViewCommandEventArgs.CommandSource propriedade.To access the control that raised the event, use the ListViewCommandEventArgs.CommandSource property.
Para obter mais informações sobre como lidar com eventos, consulte manipulando e gerando eventos.For more information about how to handle events, see Handling and Raising Events.