DataKeyArray.GetEnumerator Method ()


Returns an enumerator that contains all DataKey objects in the collection.

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

public IEnumerator GetEnumerator()

Return Value

Type: System.Collections.IEnumerator

An System.Collections.IEnumerator-implemented object that contains all DataKey objects in the collection.

Use the GetEnumerator method to get an enumerator that can be iterated through linearly to access each item in the collection. To access the item at the current position in the enumerator, use the IEnumerator.Current property. Use the IEnumerator.MoveNext method to move to the next item in the collection. To move the enumerator to its initial position, use the IEnumerator.Reset method.


When you initially get the enumerator or use the IEnumerator.Reset method to move the enumerator to the first item in the collection, you must call the IEnumerator.MoveNext method. Otherwise, the item represented by the IEnumerator.Current property is undefined.

The following code example demonstrates how to iterate through the enumerator created by the GetEnumerator method.

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">

  void CustomerGridView_DataBound(Object sender, EventArgs e)

    // Use the Count property to determine whether the
    // DataKeys collection contains any items.
    if (CustomerGridView.DataKeys.Count > 0)

      MessageLabel.Text = "The primary key of each record displayed are: <br/><br/>";

      // Use the GetEnumerator method to create an enumerator that 
      // contains the DataKey objects for the GridView control.
      IEnumerator keyEnumerator = CustomerGridView.DataKeys.GetEnumerator();

      // Iterate though the enumerator and display the primary key
      // value of each record displayed.
      while (keyEnumerator.MoveNext())
        DataKey key = (DataKey)keyEnumerator.Current;
        MessageLabel.Text += key.Value.ToString() + "<br/>";

      MessageLabel.Text = "No DataKey objects.";



<html xmlns="" >

  <head runat="server">
    <title>DataKeyArray Example</title>
    <form id="form1" runat="server">

      <h3>DataKeyArray Example</h3>

        <asp:gridview id="CustomerGridView"



        <asp:label id="MessageLabel"

        <!-- 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="CustomerDataSource"
          selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
          connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 


.NET Framework
Available since 2.0
Return to top