로드 메서드

Load 메서드를 사용하여 데이터 소스의 행과 함께 DataTable을 로드할 수 있습니다. 이 메서드는 매우 간단한 형식으로 DataReader 단일 매개 변수를 승인하는 오버로드된 메서드입니다. 이러한 형식으로는 DataTable을 행과 함께 로드하는 기능만 합니다. 필요에 따라 LoadOption 매개 변수를 지정하여 DataTable에 데이터를 추가하는 방식을 제어할 수도 있습니다.

LoadOption 매개 변수는 데이터 원본에서 들어오는 데이터를 테이블에 이미 들어 있는 데이터와 결합하는 방법을 설명하므로, DataTable에 데이터 행이 이미 들어 있는 경우에 특히 유용합니다. 예를 들어 PreserveCurrentValues(기본값)는 DataTable의 행이 Added로 표시되는 경우 Original 값이나 각 열이 데이터 원본의 일치하는 행 내용으로 설정되도록 지정합니다. Current 값은 행이 추가되었을 때 할당된 값을 유지하며 행의 RowStateChanged로 설정됩니다.

다음 표에서는 LoadOption 열거형 값에 대해 간략하게 설명합니다.

LoadOption 값 설명
OverwriteRow 들어오는 행과 DataTable에 이미 들어 있는 행의 PrimaryKey 값이 같으면 각 열의 OriginalCurrent 값이 들어오는 행의 값으로 대체되고 RowState 속성은 Unchanged로 설정됩니다.

DataTable에 없는 데이터 원본의 행이 추가되며, 해당 행의 RowState 값은 Unchanged로 설정됩니다.

이 옵션을 적용하면 데이터 원본의 내용과 일치하도록 DataTable의 내용을 새로 고칩니다.
PreserveCurrentValues(기본값) 들어오는 행과 DataTable에 이미 들어 있는 행의 PrimaryKey 값이 같으면 Original 값은 들어오는 행의 내용으로 설정되고 Current 값은 변경되지 않습니다.

RowStateAdded 또는 Modified인 경우 Modified로 설정됩니다.

RowStateDeleted였으면 Deleted로 유지됩니다.

DataTable에 없는 데이터 원본의 행이 추가되며, 해당 행의 RowStateUnchanged로 설정됩니다.
UpdateCurrentValues 들어오는 행과 DataTable에 이미 들어 있는 행의 PrimaryKey 값이 같으면 Current 값이 Original 값에 복사된 다음 Current 값이 들어오는 행의 내용으로 설정됩니다.

DataTableRowStateAdded였으면 RowStateAdded로 유지됩니다. 행이 Modified 또는 Deleted로 표시된 경우 RowStateModified입니다.

DataTable에 없는 데이터 원본의 행이 추가되며, 해당 행의 RowStateAdded로 설정됩니다.

다음 샘플에서는 Load 메서드를 사용하여 Northwind 데이터베이스에 직원 생일 목록을 표시합니다.

Private Sub LoadBirthdays(ByVal connectionString As String)  
    ' Assumes that connectionString is a valid connection string  
    ' to the Northwind database on SQL Server.  
    Dim queryString As String = _  
    "SELECT LastName, FirstName, BirthDate " & _  
      " FROM dbo.Employees " & _  
      "ORDER BY BirthDate, LastName, FirstName"  
  
    ' Open and fill a DataSet.
    Dim adapter As SqlDataAdapter = New SqlDataAdapter( _  
        queryString, connectionString)  
    Dim employees As New DataSet  
    adapter.Fill(employees, "Employees")  
  
    ' Create a SqlDataReader for use with the Load Method.  
    Dim reader As DataTableReader = employees.GetDataReader()  
  
    ' Create an instance of DataTable and assign the first  
    ' DataTable in the DataSet.Tables collection to it.  
    Dim dataTableEmp As DataTable = employees.Tables(0)  
  
    ' Fill the DataTable with data by calling Load and  
    ' passing the SqlDataReader.  
    dataTableEmp.Load(reader, LoadOption.OverwriteRow)  
  
    ' Loop through the rows collection and display the values  
    ' in the console window.  
    Dim employeeRow As DataRow  
    For Each employeeRow In dataTableEmp.Rows  
        Console.WriteLine("{0:MM\\dd\\yyyy}" & ControlChars.Tab & _  
          "{1}, {2}", _  
          employeeRow("BirthDate"), _  
          employeeRow("LastName"), _  
          employeeRow("FirstName"))  
    Next employeeRow  
  
    ' Keep the window opened to view the contents.  
    Console.ReadLine()  
End Sub  

참고 항목