GridView.OnSelectedIndexChanged(EventArgs) Método

Definição

Aciona o evento SelectedIndexChanged.

protected:
 virtual void OnSelectedIndexChanged(EventArgs ^ e);
protected virtual void OnSelectedIndexChanged (EventArgs e);
abstract member OnSelectedIndexChanged : EventArgs -> unit
override this.OnSelectedIndexChanged : EventArgs -> unit
Protected Overridable Sub OnSelectedIndexChanged (e As EventArgs)

Parâmetros

e
EventArgs

Um EventArgs que contém dados do evento.

Exemplos

O exemplo a seguir mostra como criar um manipulador de eventos para o SelectedIndexChanged evento. Neste exemplo, a linha selecionada é mantida no estado de exibição. Portanto, mesmo após uma classificação ou uma operação de paginação, somente essa linha será selecionada.

<%@ 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 ContactsGridView_SelectedIndexChanged(object sender, EventArgs e)
  {
    if (ContactsGridView.SelectedIndex >= 0)
      ViewState["SelectedKey"] = ContactsGridView.SelectedValue;
    else
      ViewState["SelectedKey"] = null;
  }

  protected void ContactsGridView_DataBound(object sender, EventArgs e)
  {
    for (int i = 0; i < ContactsGridView.Rows.Count; i++)
    {
      // Ignore values that cannot be cast as integer.
      try
      {
        if ((int)ContactsGridView.DataKeys[i].Value == (int)ViewState["SelectedKey"])
          ContactsGridView.SelectedIndex = i;
      }
      catch { }
    }
  }

  protected void ContactsGridView_Sorting(object sender, GridViewSortEventArgs e)
  {
    ContactsGridView.SelectedIndex = -1;
  }

  protected void ContactsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
    ContactsGridView.SelectedIndex = -1;
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>GridView OnSelectedIndexChanged Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView OnSelectedIndexChanged Example</h3>
      
      <asp:GridView ID="ContactsGridView"
        DataSourceID="ContactsDataSource" 
        DataKeyNames="ContactID"        
        AutoGenerateSelectButton="True"
        OnSelectedIndexChanged="ContactsGridView_SelectedIndexChanged"        
        AllowPaging="True" AllowSorting="True" 
        OnDataBound="ContactsGridView_DataBound" 
        OnSorting="ContactsGridView_Sorting" 
        OnPageIndexChanging="ContactsGridView_PageIndexChanging"
        runat="server">
        <SelectedRowStyle BackColor="Aqua" />
      </asp:GridView>
            
      <!-- 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="ContactsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ContactID], [FirstName], [LastName] FROM Person.Contact">
      </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 ContactsGridView_SelectedIndexChanged()
    If ContactsGridView.SelectedIndex >= 0 Then
      ViewState("SelectedKey") = ContactsGridView.SelectedValue
    Else
      ViewState("SelectedKey") = Nothing
    End If
  End Sub

  Protected Sub ContactsGridView_DataBound()
    For i As Integer = 0 To ContactsGridView.Rows.Count - 1
      ' Ignore values that cannot be cast as integer.
      Try
        If Convert.ToInt32(ContactsGridView.DataKeys(i).Value) = Convert.ToInt32(ViewState("SelectedKey")) Then _
          ContactsGridView.SelectedIndex = i
      Catch
      End Try
    Next
  End Sub

  Protected Sub ContactsGridView_Sorting()
    ContactsGridView.SelectedIndex = -1
  End Sub

  Protected Sub ContactsGridView_PageIndexChanging()
    ContactsGridView.SelectedIndex = -1
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>GridView OnSelectedIndexChanged Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView OnSelectedIndexChanged Example</h3>
      
      <asp:GridView ID="ContactsGridView"
        DataSourceID="ContactsDataSource" 
        DataKeyNames="ContactID"        
        AutoGenerateSelectButton="True"
        OnSelectedIndexChanged="ContactsGridView_SelectedIndexChanged"        
        AllowPaging="True" AllowSorting="True" 
        OnDataBound="ContactsGridView_DataBound" 
        OnSorting="ContactsGridView_Sorting" 
        OnPageIndexChanging="ContactsGridView_PageIndexChanging"
        runat="server">
        <SelectedRowStyle BackColor="Aqua" />
      </asp:GridView>
            
      <!-- 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="ContactsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ContactID], [FirstName], [LastName] FROM Person.Contact">
      </asp:SqlDataSource>


    </form>
  </body>
</html>

Comentários

O SelectedIndexChanged evento é acionado quando o botão Selecionar de uma linha é clicado, mas depois que o GridView controle manipula a operação de seleção. Isso permite que você forneça um método de manipulação de eventos que executa uma rotina personalizada, como atualizar um rótulo status com a linha selecionada no momento, sempre que esse evento ocorrer.

A geração de um evento invoca o manipulador de eventos por meio de um delegado. Para obter mais informações, consulte Manipulando e levantando eventos.

O OnSelectedIndexChanged método também permite que classes derivadas manipulem o evento sem anexar um delegado. Essa é a técnica preferencial para lidar com o evento em uma classe derivada.

Notas aos Herdeiros

Ao substituir OnSelectedIndexChanged(EventArgs) em uma classe derivada, chame o método da OnSelectedIndexChanged(EventArgs) classe base para que os delegados registrados recebam o evento.

Aplica-se a

Confira também