Title | Copy objects to and from the Clipboard in VB .NET |
Description | This example shows how to copy objects to and from the Clipboard in VB .NET. The trick is setting the Serializable attribute on the class you will copy to the Clipboard so the Clipboard can serialize and deserialize it. |
Keywords | Clipboard, object, VB.NET |
Categories | VB.NET, Tips and Tricks |
|
|
The trick is setting the Serializable attribute on the class you will copy to and from the Clipboard so the Clipboard serialize and deserialize it. The serialization and deserialization happen automatically; you just need to set this attribute.
|
|
<Serializable()> _
Public Class Employee
Public FirstName As String
Public LastName As String
Public Sub New()
End Sub
Public Sub New(ByVal first_name As String, ByVal _
last_name As String)
FirstName = first_name
LastName = last_name
End Sub
End Class
|
|
To copy an object to the clipboard, the program simply passes the object to the Clipboard's SetDataObject method.
|
|
Private Sub btnCopy_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCopy.Click
Dim emp As New Employee(txtFirstName.Text, _
txtLastName.Text)
Clipboard.SetDataObject(emp)
End Sub
|
|
To paste the object, the program uses the Clipboard's GetDataObject to get the IDataObject that holds the Clipboard's data.
The code then uses the data object's GetDataPresent method to see if the Clipboard contains data of the type howto_net_clipboard_object.Employee. The value howto_net_clipboard_object is the program's root namespace and the Employee class is defined inside that namespace.
If this kind of data is present, then the program uses the data object's GetData method to get the data in that format. It casts the result into an Employee object and displays the resulting object's fields.
|
|
Private Sub btnPaste_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPaste.Click
Dim data_object As IDataObject = Clipboard.GetDataObject
If data_object.GetDataPresent("howto_net_clipboard_object.Employee") _
Then
Dim emp As Employee = _
DirectCast(data_object.GetData("howto_net_clipboard_object.Employee"), _
Employee)
txtDropFirstName.Text = emp.FirstName
txtDropLastName.Text = emp.LastName
Else
txtDropFirstName.Text = ""
txtDropLastName.Text = ""
End If
End Sub
|
|
|
|