DataKeyCollection Classe

Definição

Representa uma coleção que contém o campo de chave de cada registro em uma fonte de dados.Represents a collection that contains the key field of each record in a data source. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class DataKeyCollection sealed : System::Collections::ICollection
public sealed class DataKeyCollection : System.Collections.ICollection
type DataKeyCollection = class
    interface ICollection
    interface IEnumerable
Public NotInheritable Class DataKeyCollection
Implements ICollection
Herança
DataKeyCollection
Implementações

Exemplos


<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
    <title>BaseDataList DataKeys Example</title>
<script runat="server">

      ICollection CreateDataSource() 
      {
      
         // Create sample data for the DataGrid control.
         DataTable dt = new DataTable();
         DataRow dr;
 
         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

         // Define the primary key for the table as the IntegerValue 
         // column (column 0). To do this, first create an array of 
         // DataColumns to represent the primary key. The primary key can
         // consist of multiple columns, but in this example, only
         // one column is used.
         DataColumn[] keys = new DataColumn[1];
         keys[0] = dt.Columns[0];

         // Then assign the array to the PrimaryKey property of the DataTable. 
         dt.PrimaryKey = keys;
 
         // Populate the table with sample values.
         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         }

         // To persist the data source between posts to the server, 
         // store it in session state.  
         Session["Source"] = dt;
 
         DataView dv = new DataView(dt);
         return dv;

      }
 
      void Page_Load(Object sender, EventArgs e) 
      {
 
         // Load sample data only once, when the page is first loaded.
         if (!IsPostBack) 
         {
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
         }

      }

      void Delete_Command(Object sender, DataGridCommandEventArgs e)
      {

         // Retrieve the data table from session state.
         DataTable dt = (DataTable)Session["Source"];

         // Retrieve the data row to delete from the data table. 
         // Use the DataKeys property of the DataGrid control to get 
         // the primary key value of the selected row. 
         // Search the Rows collection of the data table for this value. 
         DataRow row;
         row = dt.Rows.Find(ItemsGrid.DataKeys[e.Item.ItemIndex]);

         // Delete the item selected in the DataGrid from the data source.
         if(row != null)
         {
            dt.Rows.Remove(row);
         }

         // Save the data source.
         Session["Source"] = dt;

         // Create a DataView and bind it to the DataGrid control.
         DataView dv = new DataView(dt);
         ItemsGrid.DataSource = dv;
         ItemsGrid.DataBind();

      }

   </script>

</head>

<body>

   <form id="form1" runat="server">

      <h3>BaseDataList DataKeys Example</h3>

      <asp:DataGrid id="ItemsGrid" 
           BorderColor="Black"
           ShowFooter="False" 
           CellPadding="3" 
           CellSpacing="0"
           HeaderStyle-BackColor="#aaaadd"
           DataKeyField="IntegerValue"
           OnDeleteCommand="Delete_Command"
           runat="server">

         <Columns>

            <asp:ButtonColumn Text="Delete"
                 CommandName="Delete"/>

         </Columns>

      </asp:DataGrid>

   </form>

</body>
</html>


<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
    <title>BaseDataList DataKeys and DataKeyField Example</title>
<script runat="server">

      Function CreateDataSource() As ICollection 
      
         ' Create sample data for the DataGrid control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow
 
         ' Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", GetType(Integer)))
         dt.Columns.Add(new DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(new DataColumn("CurrencyValue", GetType(Double)))

         ' Define the primary key for the table as the IntegerValue 
         ' column (column 0). To do this, first create an array of 
         ' DataColumns to represent the primary key. The primary key can
         ' consist of multiple columns, but in this example, only
         ' one column is used.
         Dim keys(1) As DataColumn
         keys(0) = dt.Columns(0)

         ' Then assign the array to the PrimaryKey property of the DataTable. 
         dt.PrimaryKey = keys
 
         ' Populate the table with sample values.
         Dim i As Integer

         For i = 0 To 8 
     
            dr = dt.NewRow()
 
            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * (i + 1)
 
            dt.Rows.Add(dr)

         Next

         ' To persist the data source between posts to the server, 
         ' store it in session state.  
         Session("Source") = dt
 
         Dim dv As DataView = New DataView(dt)
         Return dv

      End Function
 
      Sub Page_Load(sender As Object, e As EventArgs) 
 
         ' Load sample data only once, when the page is first loaded.
         If Not IsPostBack Then 
        
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
         
         End If

      End Sub

      Sub Delete_Command(sender As Object, e As DataGridCommandEventArgs)

         ' Retrieve the data table from session state.
         Dim dt As DataTable = CType(Session("Source"), DataTable)

         ' Retrieve the data row to delete from the data table. 
         ' Use the DataKeys property of the DataGrid control to get 
         ' the primary key value of the selected row. 
         ' Search the Rows collection of the data table for this value. 
         Dim row As DataRow
         row = dt.Rows.Find(ItemsGrid.DataKeys(e.Item.ItemIndex))

         ' Delete the item selected in the DataGrid from the data source.
         If Not row is Nothing Then
         
            dt.Rows.Remove(row)
         
         End If

         ' Save the data source.
         Session("Source") = dt

         ' Create a DataView and bind it to the DataGrid control.
         Dim dv As DataView = New DataView(dt)
         ItemsGrid.DataSource = dv
         ItemsGrid.DataBind()

      End Sub

   </script>

</head>

<body>

   <form id="form1" runat="server">

      <h3>BaseDataList DataKeys and DataKeyField Example</h3>

      <asp:DataGrid id="ItemsGrid" 
           BorderColor="Black"
           ShowFooter="False" 
           CellPadding="3" 
           CellSpacing="0"
           HeaderStyle-BackColor="#aaaadd"
           DataKeyField="IntegerValue"
           OnDeleteCommand="Delete_Command"
           runat="server">

         <Columns>

            <asp:ButtonColumn Text="Delete"
                 CommandName="Delete"/>

         </Columns>

      </asp:DataGrid>

   </form>

</body>
</html>

Comentários

A DataKeyCollection classe representa uma coleção dos campos de chave na fonte de dados.The DataKeyCollection class represents a collection of the key fields in the data source. O campo de chave de cada registro na fonte de dados é armazenado nesta coleção.The key field of each record in the data source is stored in this collection. Isso permite que você armazene o campo de chave com um controle de listagem de dados sem exibi-lo no controle.This allows you to store the key field with a data listing control without displaying it in the control. Essa coleção é preenchida automaticamente com os valores do campo especificado pela BaseDataList.DataKeyField propriedade.This collection is automatically filled with the values from the field specified by the BaseDataList.DataKeyField property. Esta coleção não permite adicionar ou remover itens manualmente da coleção.This collection does not allow you to manually add or remove items from the collection.

O campo de chave é comumente usado em um manipulador para um evento, ItemCommand como ou DeleteCommand, como parte de uma cadeia de caracteres de consulta Update para revisar um registro específico na fonte de dados.The key field is commonly used in a handler for an event, such as ItemCommand or DeleteCommand, as part of an update query string to revise a specific record in the data source. O campo chave ajuda a atualizar a cadeia de caracteres de consulta para identificar o registro apropriado a ser modificado.The key field helps the update query string identify the appropriate record to modify.

Use a Count propriedade para determinar o número de itens na coleção.Use the Count property to determine the number of items in the collection. Para recuperar programaticamente um campo de DataKeyCollectionchave de um, use um dos seguintes métodos:To programmatically retrieve a key field from a DataKeyCollection, use one of following methods:

  • Use o indexador para obter um único campo de chave da coleção, usando a notação de matriz.Use the indexer to get a single key field from the collection, using array notation.

  • Use o CopyTo método para copiar o conteúdo da coleção para um System.Array objeto, que pode ser usado para obter itens da coleção.Use the CopyTo method to copy the contents of the collection to a System.Array object, which can then be used to get items from the collection.

  • Use o GetEnumerator método para criar um System.Collections.IEnumerator objeto implementado, que pode ser usado para obter itens da coleção.Use the GetEnumerator method to create a System.Collections.IEnumerator implemented object, which can then be used to get items from the collection.

Construtores

DataKeyCollection(ArrayList)

Inicializa uma nova instância da classe DataKeyCollection.Initializes a new instance of the DataKeyCollection 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 DataKeyCollection podem ser modificados.Gets a value indicating whether items in the DataKeyCollection can be modified.

IsSynchronized

Obtém um valor que indica se a DataKeyCollection é sincronizada (thread-safe).Gets a value indicating whether the DataKeyCollection is synchronized (thread-safe).

Item[Int32]

Obtém o campo de chave no índice especificado na coleção.Gets the key field at the specified index in the collection.

SyncRoot

Obtém o objeto usado para sincronizar o acesso à DataKeyCollection.Gets the object used to synchronize access to the DataKeyCollection.

Métodos

CopyTo(Array, Int32)

Copia todos os itens da DataKeyCollection para o objeto Array especificado, começando no índice especificado no objeto Array.Copies all the items from the DataKeyCollection to the specified Array object, starting at the specified index in the Array object.

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()

Cria um objeto implementado por IEnumerator que contém todos os campos de chave na DataKeyCollection.Creates a IEnumerator implemented object that contains all key fields in the DataKeyCollection.

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)

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