다음을 통해 공유


DataTable 클래스

메모리에 있는 데이터로 구성된 하나의 테이블을 나타냅니다.

네임스페이스: System.Data
어셈블리: System.Data(system.data.dll)

구문

‘선언
<SerializableAttribute> _
Public Class DataTable
    Inherits MarshalByValueComponent
    Implements IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable, _
    IXmlSerializable
‘사용 방법
Dim instance As DataTable
[SerializableAttribute] 
public class DataTable : MarshalByValueComponent, IListSource, ISupportInitializeNotification, ISupportInitialize, 
    ISerializable, IXmlSerializable
[SerializableAttribute] 
public ref class DataTable : public MarshalByValueComponent, IListSource, ISupportInitializeNotification, ISupportInitialize, 
    ISerializable, IXmlSerializable
/** @attribute SerializableAttribute() */ 
public class DataTable extends MarshalByValueComponent implements IListSource, ISupportInitializeNotification, 
    ISupportInitialize, ISerializable, IXmlSerializable
SerializableAttribute 
public class DataTable extends MarshalByValueComponent implements IListSource, ISupportInitializeNotification, 
    ISupportInitialize, ISerializable, IXmlSerializable

설명

DataTable은 ADO.NET 라이브러리의 중심 개체입니다. DataTable을 사용하는 다른 개체에는 DataSetDataView가 포함됩니다.

DataTable 개체에 액세스할 때는 조건에 따라 대/소문자가 구분됩니다. 예를 들어, 두 DataTable의 이름이 각각 "mydatatable"과 "Mydatatable"인 경우에는 두 테이블 중 하나를 검색하는 데 사용되는 문자열에서 대/소문자를 구분합니다. 그러나 "mydatatable"은 있고 "Mydatatable"은 없는 경우에는 검색 문자열에서 대/소문자를 구분하지 않습니다. TableName 속성 값은 동일하지만 Namespace 속성 값은 다른 두 개의 DataTable 개체가 DataSet에 포함할 수 있습니다. DataTable 개체 작업에 대한 자세한 내용은 DataTable 만들기을 참조하십시오.

프로그래밍 방식으로 DataTable을 만드는 경우 Columns 속성을 통해 액세스하는 DataColumnCollectionDataColumn 개체를 추가하여 스키마를 먼저 정의해야 합니다. DataColumn 개체 추가에 대한 자세한 내용은 테이블에 열 추가을 참조하십시오.

DataTable에 행을 추가하려면 먼저 NewRow 메서드를 사용하여 새 DataRow 개체를 반환해야 합니다. NewRow 메서드는 테이블의 DataColumnCollection에서 정의된 DataTable의 스키마가 있는 행을 반환합니다. DataTable에는 행을 최대 16,777,216개까지 저장할 수 있습니다. 자세한 내용은 테이블에 데이터 추가을 참조하십시오.

또한 DataTable에는 데이터 무결성을 보장하는 데 사용할 수 있는 Constraint 개체의 컬렉션이 들어 있습니다. 자세한 내용은 테이블에 제약 조건 추가를 참조하십시오.

RowChanged, RowChanging, RowDeletingRowDeleted와 같이 테이블이 변경될 때 이를 확인하는 데 사용할 수 있는 여러 DataTable 이벤트가 있습니다. DataTable과 함께 사용할 수 있는 이벤트에 대한 자세한 내용은 DataTable 이벤트 사용을 참조하십시오.

DataTable의 인스턴스를 만드는 경우 일부 읽기/쓰기 속성이 초기 값으로 설정됩니다. 이러한 값의 목록은 System.Data.DataTable 생성자 항목을 참조하십시오.

참고

DataSetDataTable 개체는 MarshalByValueComponent에서 상속되며 .NET Framework Remoting을 위한 ISerializable 인터페이스를 지원합니다. 이 두 개체는 .NET Framework Remoting에 사용할 수 있는 유일한 ADO.NET 개체입니다.

항목 위치
방법: DataTable 만들기 Data Access in Visual Studio
방법: DataTable 만들기 Visual Studio의 데이터 액세스

예제

다음 예제에서는 두 개의 DataTable 개체와 하나의 DataRelation 개체를 만들고 해당 새 개체를 DataSet에 추가합니다. 그런 다음 해당 테이블을 DataGridView 컨트롤에 표시합니다.

' Put the next line into the Declarations section.
private dataSet As DataSet 
 
Private Sub MakeDataTables()
    ' Run all of the functions. 
    MakeParentTable()
    MakeChildTable()
    MakeDataRelation()
    BindToDataGrid()
End Sub
 
Private Sub MakeParentTable()
    ' Create a new DataTable.
    Dim table As DataTable = new DataTable("ParentTable")

    ' Declare variables for DataColumn and DataRow objects.
    Dim column As DataColumn 
    Dim row As DataRow 
 
    ' Create new DataColumn, set DataType, ColumnName 
    ' and add to DataTable.    
    column = New DataColumn()
    column.DataType = System.Type.GetType("System.Int32")
    column.ColumnName = "id"
    column.ReadOnly = True
    column.Unique = True

    ' Add the Column to the DataColumnCollection.
    table.Columns.Add(column)
 
    ' Create second column.
    column = New DataColumn()
    column.DataType = System.Type.GetType("System.String")
    column.ColumnName = "ParentItem"
    column.AutoIncrement = False
    column.Caption = "ParentItem"
    column.ReadOnly = False
    column.Unique = False

    ' Add the column to the table.
    table.Columns.Add(column)
 
    ' Make the ID column the primary key column.
    Dim PrimaryKeyColumns(0) As DataColumn
    PrimaryKeyColumns(0)= table.Columns("id")
    table.PrimaryKey = PrimaryKeyColumns
 
    ' Instantiate the DataSet variable.
    dataSet = New DataSet()

    ' Add the new DataTable to the DataSet.
    dataSet.Tables.Add(table)
 
    ' Create three new DataRow objects and add 
    ' them to the DataTable
    Dim i As Integer
    For i = 0 to 2
       row = table.NewRow()
       row("id") = i
       row("ParentItem") = "ParentItem " + i.ToString()
       table.Rows.Add(row)
    Next i
End Sub
 
Private Sub MakeChildTable()
    ' Create a new DataTable.
    Dim table As DataTable = New DataTable("childTable")
    Dim column As DataColumn 
    Dim row As DataRow 
 
    ' Create first column and add to the DataTable.
    column = New DataColumn()
    column.DataType= System.Type.GetType("System.Int32")
    column.ColumnName = "ChildID"
    column.AutoIncrement = True
    column.Caption = "ID"
    column.ReadOnly = True
    column.Unique = True

    ' Add the column to the DataColumnCollection.
    table.Columns.Add(column)
 
    ' Create second column.
    column = New DataColumn()
    column.DataType= System.Type.GetType("System.String")
    column.ColumnName = "ChildItem"
    column.AutoIncrement = False
    column.Caption = "ChildItem"
    column.ReadOnly = False
    column.Unique = False
    table.Columns.Add(column)
 
    ' Create third column.
    column = New DataColumn()
    column.DataType= System.Type.GetType("System.Int32")
    column.ColumnName = "ParentID"
    column.AutoIncrement = False
    column.Caption = "ParentID"
    column.ReadOnly = False
    column.Unique = False
    table.Columns.Add(column)
 
    dataSet.Tables.Add(table)

    ' Create three sets of DataRow objects, five rows each, 
    ' and add to DataTable.
    Dim i As Integer
    For i = 0 to 4
       row = table.NewRow()
       row("childID") = i
       row("ChildItem") = "Item " + i.ToString()
       row("ParentID") = 0 
       table.Rows.Add(row)
    Next i
    For i = 0 to 4
       row = table.NewRow()
       row("childID") = i + 5
       row("ChildItem") = "Item " + i.ToString()
       row("ParentID") = 1 
       table.Rows.Add(row)
    Next i
    For i = 0 to 4
       row = table.NewRow()
       row("childID") = i + 10
       row("ChildItem") = "Item " + i.ToString()
       row("ParentID") = 2 
       table.Rows.Add(row)
    Next i
End Sub
 
Private Sub MakeDataRelation()
    ' DataRelation requires two DataColumn 
    ' (parent and child) and a name.
    Dim parentColumn As DataColumn = _
        dataSet.Tables("ParentTable").Columns("id")
    Dim childColumn As DataColumn = _
        dataSet.Tables("ChildTable").Columns("ParentID")
    Dim relation As DataRelation = new _
        DataRelation("parent2Child", parentColumn, childColumn)
    dataSet.Tables("ChildTable").ParentRelations.Add(relation)
End Sub
 
Private Sub BindToDataGrid()
    ' Instruct the DataGrid to bind to the DataSet, with the 
    ' ParentTable as the topmost DataTable.
    DataGrid1.SetDataBinding(dataSet,"ParentTable")
End Sub
 
// Put the next line into the Declarations section.
private System.Data.DataSet dataSet;
 
private void MakeDataTables()
{
    // Run all of the functions. 
    MakeParentTable();
    MakeChildTable();
    MakeDataRelation();
    BindToDataGrid();
}
 
private void MakeParentTable()
{
    // Create a new DataTable.
    System.Data.DataTable table = new DataTable("ParentTable");
    // Declare variables for DataColumn and DataRow objects.
    DataColumn column;
    DataRow row;
 
    // Create new DataColumn, set DataType, 
    // ColumnName and add to DataTable.    
    column = new DataColumn();
    column.DataType = System.Type.GetType("System.Int32");
    column.ColumnName = "id";
    column.ReadOnly = true;
    column.Unique = true;
    // Add the Column to the DataColumnCollection.
    table.Columns.Add(column);
 
    // Create second column.
    column = new DataColumn();
    column.DataType = System.Type.GetType("System.String");
    column.ColumnName = "ParentItem";
    column.AutoIncrement = false;
    column.Caption = "ParentItem";
    column.ReadOnly = false;
    column.Unique = false;
    // Add the column to the table.
    table.Columns.Add(column);
 
    // Make the ID column the primary key column.
    DataColumn[] PrimaryKeyColumns = new DataColumn[1];
    PrimaryKeyColumns[0] = table.Columns["id"];
    table.PrimaryKey = PrimaryKeyColumns;
 
    // Instantiate the DataSet variable.
    dataSet = new DataSet();
    // Add the new DataTable to the DataSet.
    dataSet.Tables.Add(table);
 
    // Create three new DataRow objects and add 
    // them to the DataTable
    for (int i = 0; i<= 2; i++)
    {
        row = table.NewRow();
        row["id"] = i;
        row["ParentItem"] = "ParentItem " + i;
        table.Rows.Add(row);
    }
}
 
private void MakeChildTable()
{
    // Create a new DataTable.
    DataTable table = new DataTable("childTable");
    DataColumn column;
    DataRow row;
 
    // Create first column and add to the DataTable.
    column = new DataColumn();
    column.DataType= System.Type.GetType("System.Int32");
    column.ColumnName = "ChildID";
    column.AutoIncrement = true;
    column.Caption = "ID";
    column.ReadOnly = true;
    column.Unique = true;

    // Add the column to the DataColumnCollection.
    table.Columns.Add(column);
 
    // Create second column.
    column = new DataColumn();
    column.DataType= System.Type.GetType("System.String");
    column.ColumnName = "ChildItem";
    column.AutoIncrement = false;
    column.Caption = "ChildItem";
    column.ReadOnly = false;
    column.Unique = false;
    table.Columns.Add(column);
 
    // Create third column.
    column = new DataColumn();
    column.DataType= System.Type.GetType("System.Int32");
    column.ColumnName = "ParentID";
    column.AutoIncrement = false;
    column.Caption = "ParentID";
    column.ReadOnly = false;
    column.Unique = false;
    table.Columns.Add(column);
 
    dataSet.Tables.Add(table);

    // Create three sets of DataRow objects, 
    // five rows each, and add to DataTable.
    for(int i = 0; i <= 4; i ++)
    {
        row = table.NewRow();
        row["childID"] = i;
        row["ChildItem"] = "Item " + i;
        row["ParentID"] = 0 ;
        table.Rows.Add(row);
    }
    for(int i = 0; i <= 4; i ++)
    {
        row = table.NewRow();
        row["childID"] = i + 5;
        row["ChildItem"] = "Item " + i;
        row["ParentID"] = 1 ;
        table.Rows.Add(row);
    }
    for(int i = 0; i <= 4; i ++)
    {
        row = table.NewRow();
        row["childID"] = i + 10;
        row["ChildItem"] = "Item " + i;
        row["ParentID"] = 2 ;
        table.Rows.Add(row);
    }
}
 
private void MakeDataRelation()
{
    // DataRelation requires two DataColumn 
    // (parent and child) and a name.
    DataColumn parentColumn = 
        dataSet.Tables["ParentTable"].Columns["id"];
    DataColumn childColumn = 
        dataSet.Tables["ChildTable"].Columns["ParentID"];
    DataRelation relation = new 
        DataRelation("parent2Child", parentColumn, childColumn);
    dataSet.Tables["ChildTable"].ParentRelations.Add(relation);
}
 
private void BindToDataGrid()
{
    // Instruct the DataGrid to bind to the DataSet, with the 
    // ParentTable as the topmost DataTable.
    dataGrid1.SetDataBinding(dataSet,"ParentTable");
}

상속 계층 구조

System.Object
   System.ComponentModel.MarshalByValueComponent
    System.Data.DataTable

스레드로부터의 안전성

이 형식은 다중 스레드 읽기 작업에 안전합니다. 쓰기 작업을 동기화해야 합니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

DataTable 멤버
System.Data 네임스페이스

기타 리소스

DataTable 작성 및 사용