miércoles, 25 de enero de 2012

Cómo copiar objetos DataRow entre clases DataTable

Antes de utilizar el método ImportRow , debe asegurarse de que la tabla de destino tiene una estructura idéntica como la tabla de origen. En este ejemplo se utiliza el método Clone de la clase DataTable para copiar la estructura de la DataTable , incluidos todos los esquemas, relaciones y restricciones de DataTable .

Este ejemplo usa la tabla Productos que se incluye con la base de datos Neptuno de Microsoft SQL Server. Se copian las cinco primeras filas de la tabla productos en otra tabla que se crea en memoria.
  1. Cree una nueva aplicación de consola en Visual Basic .NET.
  2. Si la ventana código no está abierta, haga clic con el botón secundario en Module1.vb en la ventana Explorador de soluciones y haga clic en Ver código .
  3. Elimine todo el código de la ventana dé código.
  4. Copie el código siguiente y péguelo en la ventana código:
    Imports System.Data
    Imports System.Data.SqlClient
    Module Module1
    
        Sub Main()
            Dim ds As DataSet = New DataSet()
            Dim tblProducts As DataTable
            Dim tblProductsCopy As DataTable
    
            Dim tblProductsCount As Integer
            Dim tblProductsCopyCount As Integer
            Dim i As Integer
    
            'Change the connection string to your server.
            Dim conn As SqlConnection = New SqlConnection("Server=ServerName;database=Northwind;UID=<User ID>;PWD=<PassWord>")
            'Create the DataAdapter.
            Dim da As SqlDataAdapter = New SqlDataAdapter("Select * from products", conn)
            'Fill the DataSet with data.
            da.Fill(ds, "products")
    
            
            tblProducts = ds.Tables("products")
            tblProductsCount = tblProducts.Rows.Count
            'Write the number of rows in Products table to the screen.
            Console.WriteLine("Table tblProducts has " & tblProductsCount.ToString & " Rows")
    
            'Loop through the top five rows and write the first column to the screen.
            For i = 0 To 4
                Console.WriteLine("Row(" & i.ToString & ") = " & tblProducts.Rows(i)(1))
            Next
    
            'The Clone method makes a copy of the table structure (Schema).
            tblProductsCopy = tblProducts.Clone
            'Use ImportRow method to copy from Products table to its clone.
            For i = 0 To 4
                tblProductsCopy.ImportRow(tblProducts.Rows(i))
            Next
    
            tblProductsCopyCount = tblProductsCopy.Rows.Count
            'Write blank line.
            Console.WriteLine()
            'Write the number of rows in tblProductsCopy table to the screen.
            Console.WriteLine("Table tblProductsCopy has " & tblProductsCopyCount.ToString & " Rows")
    
            'Loop through the top five rows and write the first column to the screen.
            For i = 0 To tblProductsCopyCount - 1
                Console.WriteLine("Row(" & i.ToString & ") = " & tblProductsCopy.Rows(i)(1))
            Next
    
            'This line keeps the console open until you press ENTER.
            Console.ReadLine()
    
        End Sub
    
    End Module
         
  5. Presione la tecla F5 para generar y ejecutar el proyecto. Tenga en cuenta que el resultado del programa aparece en la ventana de comandos de la manera siguiente:
    Table tblProducts has 77 Rows
    Row(0) = Chai
    Row(1) = Chang
    Row(2) = Aniseed Syrup
    Row(3) = Chef Anton's Cajun Seasoning
    Row(4) = Chef Anton's Gumbo Mix
    
    Table tblProductsCopy has 5 Rows
    Row(0) = Chai
    Row(1) = Chang
    Row(2) = Aniseed Syrup
    Row(3) = Chef Anton's Cajun Seasoning
    Row(4) = Chef Anton's Gumbo Mix
          
  6. Cuando haya terminado, presione ENTRAR para cerrar la ventana de comandos.
back to the top

Notas adicionales

Puede utilizar el método Copy de un objeto DataTable para copiar toda la DataTable :
Dim MyDataRow As DataRow
Dim DataTable1 As New DataTable()
Dim DataTable2 As New DataTable()
Dim DataView1 As New DataView()
Dim DataSet1 as New DataSet()
' Copy the entire DataTable.
Dim dataTable2 = dataTable1.Copy()
dataSet1.Tables.Add(dataTable2)
    
también puede copiar objetos DataRow desde los resultados de una clase DataView filtrada o desde los resultados de un método SELECT . Por ejemplo:
'Copy from the results of a Select method.
For Each MydataRow In DataTable1.Select("Region = 'WA'")
  DataTable2.ImportRow(MyDataRow)
Next MyDataRow

'Copy from the results of a DataView.
DataView1 = DataTable1.DefaultView()
DataView1.RowFilter = "Region = 'WA'"
For I = 0 To Dataview1.Count - 1
  DataTable2.ImportRow(Dataview1.Item(I).Row)
Next I
    

No hay comentarios:

Publicar un comentario