GridView.RowUpdating Evento

Definición

Se produce cuando se hace clic en el botón Actualizar de una fila, pero antes de que el control GridView actualice la fila.

public:
 event System::Web::UI::WebControls::GridViewUpdateEventHandler ^ RowUpdating;
public event System.Web.UI.WebControls.GridViewUpdateEventHandler RowUpdating;
member this.RowUpdating : System.Web.UI.WebControls.GridViewUpdateEventHandler 
Public Custom Event RowUpdating As GridViewUpdateEventHandler 

Tipo de evento

Ejemplos

En el ejemplo siguiente se muestra cómo usar el RowUpdating evento para actualizar los valores del objeto de origen de datos cuando el origen de datos se establece mediante programación.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

<!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 Page_Load(object sender, EventArgs e)
  {
          
    if (!Page.IsPostBack)
    {
      // Create a new table.
      DataTable taskTable = new DataTable("TaskList");
      
      // Create the columns.
      taskTable.Columns.Add("Id", typeof(int));
      taskTable.Columns.Add("Description", typeof(string));
      taskTable.Columns.Add("IsComplete", typeof(bool) );

      //Add data to the new table.
      for (int i = 0; i < 20; i++)
      {
        DataRow tableRow = taskTable.NewRow();
        tableRow["Id"] = i;
        tableRow["Description"] = "Task " + i.ToString();
        tableRow["IsComplete"] = false;            
        taskTable.Rows.Add(tableRow);
      }

      //Persist the table in the Session object.
      Session["TaskTable"] = taskTable;

      //Bind data to the GridView control.
      BindData();
    }

  }

  protected void TaskGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
    TaskGridView.PageIndex = e.NewPageIndex;
    //Bind data to the GridView control.
    BindData();
  }

  protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
  {
    //Set the edit index.
    TaskGridView.EditIndex = e.NewEditIndex;
    //Bind data to the GridView control.
    BindData();
  }

  protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  {
    //Reset the edit index.
    TaskGridView.EditIndex = -1;
    //Bind data to the GridView control.
    BindData();
  }

  protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {    
    //Retrieve the table from the session object.
    DataTable dt = (DataTable)Session["TaskTable"];

    //Update the values.
    GridViewRow row = TaskGridView.Rows[e.RowIndex];
    dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
    dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
    dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;

    //Reset the edit index.
    TaskGridView.EditIndex = -1;

    //Bind data to the GridView control.
    BindData();
  }

  private void BindData()
  {
    TaskGridView.DataSource = Session["TaskTable"];
    TaskGridView.DataBind();
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
      <asp:GridView ID="TaskGridView" runat="server" 
        AutoGenerateEditButton="True" 
        AllowPaging="true"
        OnRowEditing="TaskGridView_RowEditing"         
        OnRowCancelingEdit="TaskGridView_RowCancelingEdit" 
        OnRowUpdating="TaskGridView_RowUpdating"
        OnPageIndexChanging="TaskGridView_PageIndexChanging">
      </asp:GridView>
    
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>

<!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 Page_Load()

    If Not Page.IsPostBack Then
      ' Create a new table.
      Dim taskTable As New DataTable("TaskList")

      ' Create the columns.
      taskTable.Columns.Add("Id", GetType(Integer))
      taskTable.Columns.Add("Description", GetType(String))
      taskTable.Columns.Add("IsComplete", GetType(Boolean))

      'Add data to the new table.
      For i = 0 To 19
        Dim tableRow = taskTable.NewRow()
        tableRow("Id") = i
        tableRow("Description") = "Task " + i.ToString()
        tableRow("IsComplete") = False
        taskTable.Rows.Add(tableRow)
      Next

      'Persist the table in the Session object.
      Session("TaskTable") = taskTable

      'Bind data to the GridView control.
      BindData()
    End If

  End Sub
  
  Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    TaskGridView.PageIndex = e.NewPageIndex
    'Bind data to the GridView control.
    BindData()
  End Sub

  Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    'Set the edit index.
    TaskGridView.EditIndex = e.NewEditIndex
    'Bind data to the GridView control.
    BindData()
  End Sub

  Protected Sub TaskGridView_RowCancelingEdit()
    'Reset the edit index.
    TaskGridView.EditIndex = -1
    'Bind data to the GridView control.
    BindData()
  End Sub

  Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    'Retrieve the table from the session object.
    Dim dt = CType(Session("TaskTable"), DataTable)

    'Update the values.
    Dim row = TaskGridView.Rows(e.RowIndex)
    dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
    dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
    dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked

    'Reset the edit index.
    TaskGridView.EditIndex = -1

    'Bind data to the GridView control.
    BindData()
  End Sub

  Private Sub BindData()
    TaskGridView.DataSource = Session("TaskTable")
    TaskGridView.DataBind()
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
      <asp:GridView ID="TaskGridView" runat="server" 
        AutoGenerateEditButton="True" 
        AllowPaging="true"
        OnRowEditing="TaskGridView_RowEditing"         
        OnRowCancelingEdit="TaskGridView_RowCancelingEdit" 
        OnRowUpdating="TaskGridView_RowUpdating"
        OnPageIndexChanging="TaskGridView_PageIndexChanging">
      </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Comentarios

El RowUpdating evento se genera cuando se hace clic en el botón Actualizar de una fila, pero antes de que el GridView control actualice la fila. Esto le permite proporcionar un método de control de eventos que realiza una rutina personalizada, como cancelar la operación de actualización, siempre que se produzca este evento.

Se pasa un GridViewUpdateEventArgs objeto al método de control de eventos, que permite determinar el índice de la fila actual e indicar que se debe cancelar la operación de actualización. Para cancelar la operación de actualización, establezca la Cancel propiedad del GridViewUpdateEventArgs objeto trueen . También puede manipular las Keyscolecciones , OldValuesy NewValues , si es necesario, antes de pasar los valores al origen de datos. Una manera común de usar estas colecciones es codificar en HTML los valores proporcionados por el usuario antes de almacenarlos en el origen de datos. Esto ayuda a evitar ataques por inyección de scripts.

Nota

Las Keyscolecciones , OldValues y NewValues solo se rellenan automáticamente cuando el GridView control está enlazado a los datos mediante la DataSourceID propiedad .

Para obtener más información acerca de cómo controlar eventos, vea controlar y provocar eventos.

Se aplica a

Consulte también