DataKeyCollection 클래스

정의

데이터 소스에서 각 레코드의 키 필드를 포함하는 컬렉션을 나타냅니다. 이 클래스는 상속될 수 없습니다.

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
상속
DataKeyCollection
구현

예제


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

설명

DataKeyCollection 클래스는 데이터 소스의 키 필드의 컬렉션을 나타냅니다. 데이터 소스에서 각 레코드의 키 필드는이 컬렉션에 저장 됩니다. 이 옵션을 사용 하면 데이터 목록 컨트롤에서 표시 하지 않고 컨트롤을 사용 하 여 키 필드를 저장할 수 있습니다. 이 컬렉션에서 지정 된 필드의 값으로 자동으로 채워집니다는 BaseDataList.DataKeyField 속성입니다. 이 컬렉션에 수동으로 추가 하거나 컬렉션에서 항목을 제거할 수 없습니다.

키 필드는 일반적으로 사용 처리기에서 이벤트와 같은 ItemCommand 또는 DeleteCommand, 데이터 원본에서 특정 레코드를 수정 하기 위한 업데이트 쿼리 문자열의 일부로. 키 필드를 수정 하려면 적절 한 레코드를 식별 하는 업데이트 쿼리 문자열을 수 있습니다.

사용 하 여는 Count 속성 컬렉션의 항목 수를 결정 합니다. 키 필드를 프로그래밍 방식으로 검색할는 DataKeyCollection, 다음 방법 중 하나를 사용 합니다.

  • 인덱서를 사용 하 여 배열 표기법을 사용 하 여 컬렉션에서 단일 키 필드를 가져옵니다.

  • 사용 하 여는 CopyTo 컬렉션의 내용을 복사 하는 메서드를 System.Array 컬렉션에서 항목을 가져오려면 다음 사용할 수 있는 개체입니다.

  • 사용 하 여는 GetEnumerator 메서드를를 System.Collections.IEnumerator 구현 된 개체를 컬렉션에서 항목을 가져오려면 다음 사용할 수 있습니다.

생성자

DataKeyCollection(ArrayList)

DataKeyCollection 클래스의 새 인스턴스를 초기화합니다.

속성

Count

컬렉션의 항목 수를 가져옵니다.

IsReadOnly

DataKeyCollection의 항목을 수정할 수 있는지 여부를 나타내는 값을 가져옵니다.

IsSynchronized

DataKeyCollection가 동기화되어 스레드로부터 안전한지 여부를 나타내는 값을 가져옵니다.

Item[Int32]

컬렉션의 지정된 인덱스에 있는 키 필드를 가져옵니다.

SyncRoot

DataKeyCollection에 대한 액세스 권한을 동기화하는 데 사용된 개체를 가져옵니다.

메서드

CopyTo(Array, Int32)

DataKeyCollection 개체의 지정된 인덱스에서 시작하여 Array에서 지정된 Array 개체로 모든 항목을 복사합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetEnumerator()

IEnumerator의 모든 키 필드를 포함하는 DataKeyCollection 구현 개체를 만듭니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

확장 메서드

Cast<TResult>(IEnumerable)

IEnumerable의 요소를 지정된 형식으로 캐스팅합니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable의 요소를 필터링합니다.

AsParallel(IEnumerable)

쿼리를 병렬화할 수 있도록 합니다.

AsQueryable(IEnumerable)

IEnumerableIQueryable로 변환합니다.

적용 대상

추가 정보