Visual Studio .NET Code Snippets:
Copy and Paste To/From a Dataset

 

''' -----------------------------------------------------------------------------
''' <summary>
''' Copies specified data rows from current dataset to clipboard
''' </summary>
''' <param name="dr">Data Rows to Copy</param>
''' <returns></returns>
''' <remarks>
''' </remarks>
''' <history>
''' [greg.pringle] 09/09/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Protected Function CopyDataRow(ByRef TargetDataSet As DataSet, ByRef dr() As DataRow,
ByVal tablenum As Integer) As Boolean

Try

' You can only retreive serializable values from clipboard
' datarow not serilizable only dataset
' create new dataset with only the row to be copied

Dim ds2 As New DataSet

Dim iow As New System.IO.MemoryStream
Dim xmlw As New Xml.XmlTextWriter(iow, System.Text.Encoding.UTF8)
Tar.WriteXmlSchema(xmlw)
xmlw.Flush()
iow.Seek(0, IO.SeekOrigin.Begin)
Dim xmlr As New Xml.XmlTextReader(iow)
xmlr.Read()
ds2.ReadXmlSchema(xmlr)

'' add all given rows to dataset
For Each dritem As DataRow In dr
   If Not dritem Is Nothing Then ds2.Tables(tablenum).Rows.Add(dritem.ItemArray)
Next
xmlr.Close()
xmlw.Close()

Clipboard.SetDataObject(ds2)
CopyDataRow = True

Catch ex As Exception

CopyDataRow = False

End Try

End Function


''' -----------------------------------------------------------------------------
''' <summary>
''' Paste a datarow from clipboard to dataset
''' </summary>
''' <param name="TargetDataSet">DataSet to put the row in</param>
''' <param name="tablenum">Number of table in dataset to put row in</param>
''' <returns></returns>
''' <remarks>
''' </remarks>
''' <history>
''' [greg.pringle] 09/09/2004 Created
''' </history>
''' -----------------------------------------------------------------------------
Protected Function PasteDataRow(ByRef TargetDataSet As DataSet, ByVal tablenum As Integer) As Boolean

Try

Dim dt As DataTable = TargetDataSet.Tables(tablenum)
If Clipboard.GetDataObject.GetDataPresent(GetType(DataSet)) Then
 Dim val() As Object

 '' Cycle through all rows in clipboard
 For Each trow As DataRow In _
 CType(Clipboard.GetDataObject.GetData(GetType(DataSet)), DataSet).Tables(tablenum).Rows

 val = trow.ItemArray
 
'' Null any autoincrement fields so we don't try to insert a duplicate key
  For Each col As Data.DataColumn In TargetDataSet.Tables(tablenum).Columns
    If col.AutoIncrement Then val(col.Ordinal) = Nothing
  Next
  dt.Rows.Add(val)
 Next
End If
PasteDataRow = True

Catch ex As Exception

PasteDataRow = False

End Try

End Function