.NET Framework Class Library
GridView..::.OnSelectedIndexChanged Method

Updated: August 2008

Raises the SelectedIndexChanged event.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
Syntax

Visual Basic (Declaration)
Protected Overridable Sub OnSelectedIndexChanged ( _
    e As EventArgs _
)
Visual Basic (Usage)
Dim e As EventArgs

Me.OnSelectedIndexChanged(e)
C#
protected virtual void OnSelectedIndexChanged(
    EventArgs e
)
Visual C++
protected:
virtual void OnSelectedIndexChanged(
    EventArgs^ e
)
JScript
protected function OnSelectedIndexChanged(
    e : EventArgs
)

Parameters

e
Type: System..::.EventArgs
An System..::.EventArgs that contains event data.
Remarks

The SelectedIndexChanged event is raised when a row's Select button is clicked, but after the GridView control handles the select operation. This enables you to provide an event-handling method that performs a custom routine, such as updating a status label with the currently selected row, whenever this event occurs.

Raising an event invokes the event handler through a delegate. For more information, see Raising an Event.

The OnSelectedIndexChanged method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

Notes to Inheritors:

When overriding OnSelectedIndexChanged in a derived class, be sure to call the base class's OnSelectedIndexChanged method so that registered delegates receive the event.

Examples

The following example shows how create an event handler for the SelectedIndexChanged event. In this example, the selected row is persisted in the view state. So even after a sorting or a paging operation, only that row will be selected.

Visual Basic
<%@ 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(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
        ContactsGridView.SelectedIndex = -1
    End Sub

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

<html >
<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>
C#
<%@ 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  >
  <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>
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0
See Also

Reference

Other Resources

Change History

Date

History

Reason

August 2008

Added a sample.

Customer feedback.

Tags :


Page view tracker