GridView.RowUpdating Événement

Définition

Se produit lors d'un clic sur le bouton Mise à jour d'une ligne, mais avant que le contrôle GridView ne mette la ligne à jour.

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 

Type d'événement

Exemples

L’exemple suivant montre comment utiliser l’événement RowUpdating pour mettre à jour les valeurs dans l’objet source de données lorsque la source de données est définie par programmation.

<%@ 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>

Remarques

L’événement RowUpdating est déclenché lorsque l’utilisateur clique sur le bouton Mettre à jour d’une ligne, mais avant que le GridView contrôle ne la met à jour. Cela vous permet de fournir une méthode de gestion des événements qui effectue une routine personnalisée, telle que l’annulation de l’opération de mise à jour, chaque fois que cet événement se produit.

Un GridViewUpdateEventArgs objet est passé à la méthode de gestion des événements, ce qui vous permet de déterminer l’index de la ligne actuelle et d’indiquer que l’opération de mise à jour doit être annulée. Pour annuler l’opération de mise à jour, définissez la Cancel propriété de l’objet GridViewUpdateEventArgs sur true. Vous pouvez également manipuler les Keyscollections , OldValueset NewValues , si nécessaire, avant que les valeurs ne soient passées à la source de données. Une façon courante d’utiliser ces collections consiste à encoder au format HTML les valeurs fournies par l’utilisateur avant qu’elles ne soient stockées dans la source de données. Cela permet d’éviter les attaques par injection de script.

Notes

Les Keyscollections , OldValues et NewValues sont automatiquement renseignées uniquement lorsque le GridView contrôle est lié aux données à l’aide de la DataSourceID propriété .

Pour plus d’informations sur la façon de gérer les événements, consultez gestion et déclenchement d’événements.

S’applique à

Voir aussi