DataKeyArray Classe

Definição

Representa uma coleção de objetos DataKey .Represents a collection of DataKey objects. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class DataKeyArray sealed : System::Collections::ICollection, System::Web::UI::IStateManager
public sealed class DataKeyArray : System.Collections.ICollection, System.Web.UI.IStateManager
type DataKeyArray = class
    interface ICollection
    interface IEnumerable
    interface IStateManager
Public NotInheritable Class DataKeyArray
Implements ICollection, IStateManager
Herança
DataKeyArray
Implementações

Exemplos

O exemplo de código a seguir demonstra como usar o indexador para recuperar DataKey um objeto de DataKeyArray uma coleção.The following code example demonstrates how to use the indexer to retrieve a DataKey object from a DataKeyArray collection.


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

  void CustomerGridView_DataBound(Object sender, EventArgs e)
  {           
    // Use the indexer to retrieve the DataKey object for the 
    // first record.
    DataKey key = CustomerGridView.DataKeys[0];

    // Display the value of the primary key for the first
    // record displayed in the GridView control.
    MessageLabel.Text = "The primary key of the first record displayed is " +
      key.Value.ToString() + ".";
  }

  void CopyArray_Click(Object sender, EventArgs e)
  {
      DataKeyArray theKeys = CustomerGridView.DataKeys;
      DataKey[] myNewArray = new DataKey[theKeys.Count];
      theKeys.CopyTo(myNewArray, 0);
      Label2.Visible = true;

      // Display first page key values from the new array.
      for (int i = 0; i < myNewArray.Length; i++)
      {
          Label2.Text += "<br />" + myNewArray[i].Value;
      }

  }

</script>

<html  >

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

      <h3>DataKeyArray Example</h3>

        <asp:gridview id="CustomerGridView"
          datasourceid="CustomerDataSource"
          autogeneratecolumns="true"
          datakeynames="CustomerID"  
          allowpaging="true"
          ondatabound="CustomerGridView_DataBound" 
          runat="server">

        </asp:gridview>

        <br/>

        <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>

        <!-- 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 %>" 
          runat="server"/>

        <asp:Button ID="CopyArray" 
            runat="server" 
            Text="Copy DataKeyArray to Array" 
            OnClick="CopyArray_Click" />

        <br />

        <asp:label id="Label2"
          runat="server"
          Visible="false"  
          Text="First page of Copied Array Key Values" />


      </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">

  Sub CustomerGridView_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles CustomerGridView.DataBound
          
    ' Use the indexer to retrieve the DataKey object for the 
    ' first record.
    Dim key As DataKey = CustomerGridView.DataKeys(0)

    ' Display the value of the primary key for the first
    ' record displayed in the GridView control.
    MessageLabel.Text = "The primary key of the first record displayed is " & _
      key.Value.ToString() & "."
  
    End Sub
    
    Sub CopyArray_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim theKeys As DataKeyArray = CustomerGridView.DataKeys
        Dim myNewArray(theKeys.Count - 1) As DataKey
        theKeys.CopyTo(myNewArray, 0)
        Label2.Visible = True

        ' Display first page key values from the new array.  
        For i As Integer = 0 To myNewArray.Length - 1
            Label2.Text &= "<br />" & myNewArray(i).Value
        Next i

    End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

  <head id="Head1" runat="server">
    <title>DataKeyArray Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DataKeyArray Example</h3>
                       
        <asp:gridview id="CustomerGridView"
          datasourceid="CustomerDataSource"
          autogeneratecolumns="true"
          datakeynames="CustomerID"  
          allowpaging="true"
          runat="server">
            
        </asp:gridview>
        
        <br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
            
        <!-- 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%>" 
          runat="server"/>

        <asp:Button ID="CopyArray" 
            runat="server" 
            Text="Copy DataKeyArray to Array" 
            OnClick="CopyArray_Click" />

        <br />

        <asp:label id="Label2"
          runat="server"
          Visible="false"  
          Text="First page of Copied Array Key Values" />
            
      </form>
  </body>
</html>

O exemplo de código a seguir demonstra como iterar DataKeyArray por meio de uma coleção.The following code example demonstrates how to iterate through a DataKeyArray collection.


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

  void CustomerGridView_DataBound(Object sender, EventArgs e)
  {    
    // Display the value of the primary key for each
    // record in the GridView control.
    MessageLabel.Text = "The primary key of each record displayed are: <br/><br/>";

    foreach (DataKey key in CustomerGridView.DataKeys)
    {
       MessageLabel.Text += key.Value.ToString() + "<br/>";
    }
  }
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

  <head runat="server">
    <title>DataKeyArray Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DataKeyArray Example</h3>
                       
        <asp:gridview id="CustomerGridView"
          datasourceid="CustomerDataSource"
          autogeneratecolumns="true"
          datakeynames="CustomerID"  
          allowpaging="true"
          ondatabound="CustomerGridView_DataBound" 
          runat="server">
            
        </asp:gridview>
        
        <br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
            
        <!-- 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%>" 
          runat="server"/>
            
      </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">

  Sub CustomerGridView_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles CustomerGridView.DataBound
    
    ' Display the value of the primary key for each
    ' record in the GridView control.
    MessageLabel.Text = "The primary key of each record displayed are: <br/><br/>"

    Dim key As DataKey
    For Each key In CustomerGridView.DataKeys
    
      MessageLabel.Text += key.Value.ToString() + "<br/>"
      
    Next
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

  <head runat="server">
    <title>DataKeyArray Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>DataKeyArray Example</h3>
                       
        <asp:gridview id="CustomerGridView"
          datasourceid="CustomerDataSource"
          autogeneratecolumns="true"
          datakeynames="CustomerID"  
          allowpaging="true"
          runat="server">
            
        </asp:gridview>
        
        <br/>
        
        <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
            
        <!-- 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%>" 
          runat="server"/>
            
      </form>
  </body>
</html>

Comentários

A DataKeyArray classe é usada para armazenar e gerenciar uma coleção de DataKey objetos.The DataKeyArray class is used to store and manage a collection of DataKey objects. Um DataKey objeto representa a chave primária de um registro em um controle de associação de dados.A DataKey object represents the primary key of a record in a data-bound control. Em geral, os controles vinculados a dados que exibem vários registros ( GridView como o controle) DataKeyArray usam um objeto para DataKey armazenar os objetos para os registros exibidos no controle.In general, data-bound controls that display multiple records (such as the GridView control) use a DataKeyArray object to store the DataKey objects for the records displayed in the control.

A DataKeyArray classe oferece suporte a várias maneiras de acessar os itens na coleção:The DataKeyArray class supports several ways to access the items in the collection:

  • Use o Item[Int32] indexador para recuperar diretamente um DataKey objeto da coleção em um índice de base zero específico.Use the Item[Int32] indexer to directly retrieve a DataKey object from the collection at a specific zero-based index.

  • Use o GetEnumerator método para recuperar um enumerador que pode ser usado para iterar pela coleção.Use the GetEnumerator method to retrieve an enumerator that can be used to iterate through the collection.

  • Use o CopyTo método para copiar os itens da coleção em uma matriz, que pode ser usada para acessar os itens na coleção.Use the CopyTo method to copy the items in the collection into an array, which can then be used to access the items in the collection.

Para determinar o número total de itens na coleção, use a Count propriedade.To determine the total number of items in the collection, use the Count property.

Construtores

DataKeyArray(ArrayList)

Inicializa uma nova instância da classe DataKeyArray.Initializes a new instance of the DataKeyArray class.

Propriedades

Count

Obtém o número de itens na coleção.Gets the number of items in the collection.

IsReadOnly

Obtém um valor que indica se os itens na coleção podem ser modificados.Gets a value indicating whether the items in the collection can be modified.

IsSynchronized

Obtém um valor que indica se a coleção DataKeyArray é sincronizada (thread-safe).Gets a value indicating whether the DataKeyArray collection is synchronized (thread safe).

Item[Int32]

Obtém o objeto DataKey da coleção no índice especificado.Gets the DataKey object from the collection at the specified index.

SyncRoot

Obtém o objeto usado para sincronizar o acesso à coleção.Gets the object used to synchronize access to the collection.

Métodos

CopyTo(DataKey[], Int32)

Copia todos os itens dessa coleção para a matriz de objetos DataKey especificada, começando no índice especificado na matriz.Copies all the items from this collection to the specified array of DataKey objects, starting at the specified index in the array.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetEnumerator()

Retorna um enumerador que contém todos os objetos DataKey na coleção.Returns an enumerator that contains all DataKey objects in the collection.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32)

Copia todos os itens dessa coleção para a Array especificada, começando no índice especificado na Array.Copies all the items from this collection to the specified Array, starting at the specified index in the Array.

IStateManager.IsTrackingViewState

Obtém um valor que indica se o objeto DataKeyArray está controlando suas alterações de estado de exibição.Gets a value indicating whether the DataKeyArray object is tracking its view-state changes.

IStateManager.LoadViewState(Object)

Carrega o estado de exibição salvo anteriormente do objeto DataKeyArray.Loads the previously saved view state of the DataKeyArray object.

IStateManager.SaveViewState()

Salva o estado de exibição atual do objeto DataKeyArray.Saves the current view state of the DataKeyArray object.

IStateManager.TrackViewState()

Marca o ponto inicial no qual começar a acompanhar e salvar as alterações de estado de exibição no objeto DataKeyArray.Marks the starting point at which to begin tracking and saving view-state changes to the DataKeyArray object.

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a

Veja também