GridViewUpdatedEventArgs Classe

Definição

Fornece dados para o evento de RowUpdated .Provides data for the RowUpdated event.

public ref class GridViewUpdatedEventArgs : EventArgs
public class GridViewUpdatedEventArgs : EventArgs
type GridViewUpdatedEventArgs = class
    inherit EventArgs
Public Class GridViewUpdatedEventArgs
Inherits EventArgs
Herança
GridViewUpdatedEventArgs

Exemplos

O exemplo a seguir mostra como determinar se uma exceção ocorreu durante uma operação de atualização.The following example shows how to determine whether an exception occurred during an update operation.


<%@ 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 CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
  {
    // Use the Exception property to determine whether an exception
    // occurred during the update operation.
    if (e.Exception == null)
    {
      // Sometimes an error might occur that does not raise an 
      // exception, but prevents the update operation from 
      // completing. Use the AffectedRows property to determine 
      // whether the record was actually updated. 
      if (e.AffectedRows == 1)
      {
        // Use the Keys property to get the value of the key field.
        String keyFieldValue = e.Keys["CustomerID"].ToString();

        // Display a confirmation message.
        Message.Text = "Record " + keyFieldValue +
          " updated successfully. ";

        // Display the new and original values.
        DisplayValues((OrderedDictionary)e.NewValues, (OrderedDictionary)e.OldValues);
      }
      else
      {
        // Display an error message.
        Message.Text = "An error occurred during the update operation.";

        // When an error occurs, keep the GridView
        // control in edit mode.
        e.KeepInEditMode = true;
      }
    }
    else
    {
      // Insert the code to handle the exception.
      Message.Text = e.Exception.Message;

      // Use the ExceptionHandled property to indicate that the 
      // exception is already handled.
      e.ExceptionHandled = true;

      e.KeepInEditMode = true;
    }
  }

  void DisplayValues(OrderedDictionary newValues, OrderedDictionary oldValues)
  {

    Message.Text += "<br/></br>";

    // Iterate through the new and old values. Display the
    // values on the page.
    for (int i = 0; i < oldValues.Count; i++)
    {
      Message.Text += "Old Value=" + oldValues[i].ToString() +
        ", New Value=" + newValues[i].ToString() + "<br/>";
    }

    Message.Text += "</br>";

  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridViewUpdatedEventArgs Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridViewUpdatedEventArgs Example</h3>
            
      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogenerateeditbutton="true"
        allowpaging="true" 
        datakeynames="CustomerID"
        onrowupdated="CustomersGridView_RowUpdated" 
        runat="server">
      </asp:gridview>
      
      <br/>
      
      <asp:label id="Message"
        forecolor="Red"          
        runat="server"/>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </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">

  Sub CustomersGridView_RowUpdated(sender As Object, e As GridViewUpdatedEventArgs)
  
    ' Use the Exception property to determine whether an exception
    ' occurred during the update operation.
    If e.Exception Is Nothing Then
    
      ' Sometimes an error might occur that does not raise an 
      ' exception, but prevents the update operation from 
      ' completing. Use the AffectedRows property to determine 
      ' whether the record was actually updated. 
      If e.AffectedRows = 1 Then
      
        ' Use the Keys property to get the value of the key field.
        Dim keyFieldValue As String = e.Keys("CustomerID").ToString()

        ' Display a confirmation message.
        Message.Text = "Record " & keyFieldValue & _
          " updated successfully. "

        ' Display the new and original values.
        DisplayValues(CType(e.NewValues, OrderedDictionary), CType(e.OldValues, OrderedDictionary))

      Else
      
        ' Display an error message.
        Message.Text = "An error occurred during the update operation."

        ' When an error occurs, keep the GridView
        ' control in edit mode.
        e.KeepInEditMode = True
        
      End If
    
    Else
    
      ' Insert the code to handle the exception.
      Message.Text = e.Exception.Message

      ' Use the ExceptionHandled property to indicate that the 
      ' exception is already handled.
      e.ExceptionHandled = True

      e.KeepInEditMode = True
    
    End If
  
  End Sub

  Sub DisplayValues(ByVal newValues As OrderedDictionary, ByVal oldValues As OrderedDictionary)

    Message.Text &= "<br/></br>"

    ' Iterate through the new and old values. Display the
    ' values on the page.
    Dim i As Integer
    For i = 0 To oldValues.Count - 1
    
      Message.Text &= "Old Value=" & oldValues(i).ToString() & _
        ", New Value=" & newValues(i).ToString() & "<br/>"
    Next

    Message.Text &= "</br>"

  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridViewUpdatedEventArgs Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridViewUpdatedEventArgs Example</h3>
            
      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogenerateeditbutton="true"
        allowpaging="true" 
        datakeynames="CustomerID"
        onrowupdated="CustomersGridView_RowUpdated" 
        runat="server">
      </asp:gridview>
      
      <br/>
      
      <asp:label id="Message"
        forecolor="Red"          
        runat="server"/>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>
            
    </form>
  </body>
</html>

Comentários

O GridView controle gera o RowUpdated evento quando um botão de atualização no controle é clicado, mas depois que o GridView controle atualiza o registro.The GridView control raises the RowUpdated event when an Update button in the control is clicked, but after the GridView control updates the record. (Um botão de atualização é um controle de botão cuja CommandName propriedade está definida como "atualizar".) Você pode executar uma rotina personalizada sempre que esse evento ocorrer, como verificar os resultados de uma operação de atualização.(An Update button is a button control whose CommandName property is set to "Update".) You can perform a custom routine whenever this event occurs, such as checking the results of an update operation.

Um GridViewUpdatedEventArgs objeto é passado para o manipulador de eventos, que permite que você determine o número de registros que foram afetados e quaisquer exceções que possam ter ocorrido.A GridViewUpdatedEventArgs object is passed to the event handler, which enables you to determine the number of records that were affected and any exceptions that might have occurred. Para determinar o número de registros que foram afetados pela operação de atualização, use a AffectedRows propriedade.To determine the number of records that were affected by the update operation, use the AffectedRows property. Para determinar se alguma exceção ocorreu, use a Exception propriedade.To determine whether any exceptions occurred, use the Exception property. Você também pode indicar se a exceção foi tratada no manipulador de eventos definindo a ExceptionHandled propriedade.You can also indicate whether the exception was handled in the event handler by setting the ExceptionHandled property.

Para acessar os valores de campo de chave para o registro atualizado, use a Keys propriedade.To access the key field values for the updated record, use the Keys property. Você pode acessar os valores de campo não chave originais usando a OldValues propriedade.You can access the original non-key field values by using the OldValues property. Você pode acessar os valores de campo não chave atualizados usando as NewValues Propriedades.You can access the updated non-key field values by using the NewValues properties.

Por padrão, o GridView controle retorna para o modo somente leitura após uma operação de atualização.By default, the GridView control returns to read-only mode after an update operation. Ao manipular uma exceção que ocorreu durante a operação de atualização, você pode manter o GridView controle no modo de edição definindo a KeepInEditMode propriedade como true .When you handle an exception that occurred during the update operation, you can keep the GridView control in edit mode by setting the KeepInEditMode property to true.

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.

Para obter uma lista de valores de propriedade inicial para uma instância da GridViewUpdatedEventArgs classe, consulte o GridViewUpdatedEventArgs Construtor.For a list of initial property values for an instance of the GridViewUpdatedEventArgs class, see the GridViewUpdatedEventArgs constructor.

Construtores

GridViewUpdatedEventArgs(Int32, Exception)

Inicializa uma nova instância da classe GridViewUpdatedEventArgs.Initializes a new instance of the GridViewUpdatedEventArgs class.

Propriedades

AffectedRows

Obtém o número de linhas afetadas pela operação de atualização.Gets the number of rows that were affected by the update operation.

Exception

Obtém a exceção (se houver) acionada durante a operação de atualização.Gets the exception (if any) that was raised during the update operation.

ExceptionHandled

Obtém ou define um valor indicando se uma exceção gerada durante a operação de atualização foi tratada no manipulador de eventos.Gets or sets a value that indicates whether an exception that was raised during the update operation was handled in the event handler.

KeepInEditMode

Obtém ou define um valor que indica se o controle GridView deve permanecer no modo de edição após uma operação de atualização.Gets or sets a value that indicates whether the GridView control should remain in edit mode after an update operation.

Keys

Obtém um dicionário que contém os pares nome-valor do campo de chave para o registro atualizado.Gets a dictionary that contains the key field name/value pairs for the updated record.

NewValues

Obtém um dicionário que contém os pares nome-valor do novo campo para o registro atualizado.Gets a dictionary that contains the new field name/value pairs for the updated record.

OldValues

Obtém um dicionário que contém os pares nome-valor de campo original para o registro atualizado.Gets a dictionary that contains the original field name/value pairs for the updated record.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Confira também