GridView.EditIndex Propiedad

Definición

Obtiene o establece el índice de la fila que se va a editar.

public:
 virtual property int EditIndex { int get(); void set(int value); };
public virtual int EditIndex { get; set; }
member this.EditIndex : int with get, set
Public Overridable Property EditIndex As Integer

Valor de propiedad

Índice de base cero de la fila que se va a editar. El valor predeterminado es -1, que indica que no se va a editar ninguna fila.

Excepciones

El índice especificado es menor que -1.

Ejemplos

En el ejemplo siguiente se muestra cómo usar la propiedad para determinar qué EditIndex fila se actualizó después de editarla en un GridView control . Se muestra un mensaje para indicar que la actualización se realizó correctamente.


<%@ 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_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    
    // Clear the message label when the user enters edit mode.
    if (e.CommandName == "Edit")
    {
      Message.Text = "";
    }
    
  }

  void CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
    {
   
        // The update operation was successful. Retrieve the row being edited.
        int index = CustomersGridView.EditIndex;
        GridViewRow row = CustomersGridView.Rows[index];
        
        // Notify the user that the update was successful.
        Message.Text = "Updated record " + row.Cells[1].Text + ".";
    
    }

  void CustomersGridView_RowCancelingEdit(Object sender, GridViewCancelEditEventArgs e)
    {
   
        // The update operation was canceled. Display the appropriate message.
        Message.Text = "Update operation canceled.";
    
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView Rows Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView Rows Example</h3>
            
      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
                
      <br/>    
            
      <!-- 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"
        allowpaging="true" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"
        onrowcommand="CustomersGridView_RowCommand"
        onrowupdated="CustomersGridView_RowUpdated"
        onrowcancelingedit="CustomersGridView_RowCancelingEdit"  
        runat="server">
      </asp:gridview>
            
      <!-- 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)"
        deletecommand="Delete from Customers 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_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
    
    ' Clear the message label when the user enters edit mode.
    If e.CommandName = "Edit" Then
      Message.Text = ""
    End If
    
  End Sub
  
  Sub CustomersGridView_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
   
    ' The update operation was successful. Retrieve the row being edited.
    Dim index As Integer = CustomersGridView.EditIndex
    Dim row As GridViewRow = CustomersGridView.Rows(index)
        
    ' Notify the user that the update was successful.
    Message.Text = "Updated record " & row.Cells(1).Text + "."
    
  End Sub

  Sub CustomersGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
   
    ' The update operation was canceled. Display the appropriate message.
    Message.Text = "Update operation canceled."
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView Rows Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView Rows Example</h3>
            
      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
                
      <br/>    
            
      <!-- 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"
        allowpaging="true" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"
        onrowcommand="CustomersGridView_RowCommand"
        onrowupdated="CustomersGridView_RowUpdated"
        onrowcancelingedit="CustomersGridView_RowCancelingEdit"  
        runat="server">
      </asp:gridview>
            
      <!-- 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)"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>
            
    </form>
  </body>
</html>

Comentarios

El índice de fila está basado en cero (la primera fila es la fila cero).

Esta propiedad se usa normalmente solo en los siguientes escenarios, que implican controladores para eventos específicos:

  • Desea que el GridView control se abra en modo de edición para una fila específica la primera vez que se muestre la página. Para ello, puede establecer la EditIndex propiedad en el controlador para el Load evento de la Page clase o del GridView control .

  • Quiere saber qué fila se editó después de actualizar la fila. Para ello, puede recuperar el índice de fila de la EditIndex propiedad en el RowUpdated controlador de eventos.

  • Está enlazando el GridView control a un origen de datos estableciendo la DataSource propiedad mediante programación. En este caso, debe establecer la EditIndex propiedad en los RowEditing controladores de eventos y RowCancelingEdit .

Si establece la EditIndex propiedad después de un postback o en controladores para eventos que se generan más adelante que el evento, es posible que el LoadGridView control no entre en el modo de edición de la fila especificada. Si lee el valor de esta propiedad en otros controladores de eventos, no se garantiza que el índice refleje la fila que se está editando.

Para determinar en qué fila el usuario ha hecho clic en un botón Editar o hipervínculo antes de que el GridView control entre en el modo de edición, puede recuperar el índice de fila de la NewEditIndex propiedad del GridViewEditEventArgs objeto en el RowEditing controlador de eventos.

Para evitar que el GridView control entre en modo de edición después de que un usuario haya hecho clic en un botón o hipervínculo Editar , establezca la Cancel propiedad del GridViewEditEventArgs objeto true en en el RowEditing controlador de eventos.

Se aplica a

Consulte también