Professional Documents
Culture Documents
VB.NET
UNIT 4 For
III-CSE
CONTENTS
DELEGATES AND EVENTS
ACCESSING DATA
ADO.NET OBJECT MODEL .NET DATA PROVIDERS DIRECT ACCESS TO DATA ACESSING DATA WITH DATASETS
2002 Prentice Hall. All rights reserved.
1. Delegates Delegates
Classes that encapsulate a set of references to methods
A delegate object that contains method references can be passed to another method
Singlecast delegates
Delegates containing a single method and they are created and derived from class Delegate
Multicast delegates
Delegates containing multiple methods and they are derived from class MulticastDelegate
AddressOf
Creates a delegate instance enclosing a reference to that method
2002 Prentice Hall. All rights reserved.
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ' Fig. 10.24: DelegateBubbleSort.vb ' Uses delegates to sort random numbers (ascending or descending). Public Class CDelegateBubbleSort
Outline
' delegate definition Public Delegate Function Comparator( _ ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean
' sort array depending on comparator Public Sub SortArray(ByVal array As Integer(), _ ByVal Compare As Comparator)
Dim i, pass As Integer
5
36 37 38 39 40 41 42 43 Dim hold As Integer
Outline
DelegateBubbleSo rt.vb
hold = firstElement firstElement = secondElement secondElement = hold End Sub ' Swap
End Class ' CDelegateBubbleSort
6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ' Fig. 10.25: FrmBubbleSort.vb ' Create GUI that enables user to sort array. Imports System.Windows.Forms Public Class CFrmBubbleSort Inherits Form
Outline
FrmBubbleSort.vb
Displays a list
of unsorted numbers
' original array with unsorted elements Dim mElementArray As Integer() = New Integer(9){}
' delegate implementation sorts in asending order Private Function SortAscending(ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean Return element1 > element2 End Function ' SortAscending
7
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 ' delegate implementation sorts in descending order Private Function SortDescending(ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean Return element1 < element2 End Function ' SortDescending ' creates random generated numbers Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click txtSorted.Clear() Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer
Outline
FrmBubbleSort.vb
' create String with 10 random numbers For i = 0 To mElementArray.GetUpperBound(0) mElementArray(i) = randomNumber.Next(100) output &= mElementArray(i) & vbCrLf Next
txtOriginal.Text = output ' display numbers
' enable sort buttons cmdSortAscending.Enabled = True cmdSortDescending.Enabled = True End Sub ' cmdCreate_Click
8
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 ' display array contents in specified TextBox Private Sub DisplayResults() Dim output As String Dim i As Integer
Outline
FrmBubbleSort.vb
' create string with sorted numbers cmdSortDescending_Click For i = 0 To mElementArray.GetUpperBound(0) are invoked when the user clicks the output &= mElementArray(i) & vbCrLf Next Sort Ascending and Sort Descending buttons txtSorted.Text = output ' display numbers End Sub ' DisplayResults ' sorts randomly generated numbers in ascending manner Private Sub cmdSortAscending_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles cmdSortAscending.Click ' sort array mBubbleSort.SortArray(mElementArray, AddressOf SortAscending) DisplayResults() ' display results cmdSortAscending.Enabled = False cmdSortDescending.Enabled = True End Sub ' cmdSortAscending_Click ' sorts randomly generated numbers in descending manner Private Sub cmdSortDescending_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles cmdSortDescending.Click ' create sort object and sort array mBubbleSort.SortArray(mElementArray, AddressOf SortDescending)
9
102 103 104 105 106 107 108 109 DisplayResults() ' display results cmdSortDescending.Enabled = False cmdSortAscending.Enabled = True End Sub ' cmdSortDescending_Click End Class ' CFrmBubbleSort
Outline
FrmBubbleSort.vb
10
Outline
FrmBubbleSort.vb
11
Outline
FrmBubbleSort.vb
12
Notion of delegates
Objects that reference methods Act as intermediaries between objects creating events and methods handling events
Event multicasting
Inclusion of multiple handlers for one event
13
callsHandler 1 for event E calls Object A raises event E Delegate for event EHandler 2 for event E Handler 3 for event E
Fig. 12.5
2002 Prentice Hall. All rights reserved.
14
Fig. 12.6
2002 Prentice Hall. All rights reserved.
15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ' Fig. 12.7: SimpleEventExample.vb ' Program demonstrating simple event handler. Public Class FrmSimple Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New()
Outline
SimpleEvenExampl e.vb
' Add any initialization after the ' InitializeComponent() call End Sub ' New ' Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose( _ ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub ' Dispose
16
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 ' Required by the Windows Form Designer Private components As System.ComponentModel.Container ' NOTE: The following procedure is required by ' the Windows Form Designer. ' It can be modified using the Windows Form Designer. ' Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.lblOutput = New System.Windows.Forms.Label() Me.SuspendLayout() ' 'lblOutput ' Me.lblOutput.Location = New System.Drawing.Point(32, 48) Me.lblOutput.Name = "lblOutput" Me.lblOutput.Size = New System.Drawing.Size(168, 40) Me.lblOutput.TabIndex = 0 Me.lblOutput.Text = "Click Me!" ' 'FrmSimple ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(272, 237) Me.Controls.AddRange( _ New System.Windows.Forms.Control() {Me.lblOutput}) Me.Name = "FrmSimple" Me.Text = "SimpleEventExample" Me.ResumeLayout(False) End of End Sub #End Region
Outline
SimpleEvenExampl e.vb
17
71 72 73 74 75 76 77 78 ' handler for click event on lblOutput Private Sub lblOutput_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles lblOutput.Click MessageBox.Show("Label was pressed") End Sub ' lblOutput_Click End Class ' FrmSimpleExample
Outline
18
ADO .NET and Object Model Provides an API for accessing database systems programmatically DataSets act as caches:
Store data from source in local memory
30
295 296 297 298 299 300 301 302 Me.ResumeLayout(False) End Sub ' InitializeComponent #End Region End Class ' FrmTableDisplay
Outline
DisplayTable.vb
31
19.6.2 Querying the Books Database Use SELECT statements on database and display results
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
' Fig. 19.28: DisplayQueryResults.vb ' Displays the contents of the authors Public Class FrmDisplayQueryResult Inherits System.Windows.Forms.Form
Form FrmDisplayQueryResult contains Outline database. TextBox txtQuery, in which users input SELECT statements DisplayQueryResu lts.vb
32
Friend WithEvents txtQuery As System.Windows.Forms.TextBox Friend WithEvents cmdSubmit As System.Windows.Forms.Button Friend WithEvents dgdResults As System.Windows.Forms.DataGrid Friend WithEvents BooksConnection As _ System.Data.OleDb.OleDbConnection Friend WithEvents BooksDataAdapter As _ System.Data.OleDb.OleDbDataAdapter Friend WithEvents BooksDataSet As System.Data.DataSet '
After entering a query, the user clicks Button cmdSubmit, Visual labeled Studio Submit .NET generated Query,code to view the results of the query
' perform SQL query on data Private Sub cmdSubmit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSubmit.Click Try ' set the text of the SQL query to what the user typed ' in BooksDataAdapter.SelectCommand.CommandText = _ txtQuery.Text ' clear the DataSet from the previous operation BooksDataSet.Clear()
33
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 ' Fill the data set with the information that results ' from the SQL query BooksDataAdapter.Fill(BooksDataSet, "Authors") ' Bind the DataGrid to the contents of the DatSet dgdResults.SetDataBinding(BooksDataSet, "Authors") ' display database connection verbose message Catch exception As System.Data.OleDb.OleDbException MessageBox.Show("Invalid Query") End Try End Sub ' cmdSubmit_Click End Class ' FrmDisplayQueryResults
Outline
DisplayQueryResu lts.vb
Program Output
34
19.8 Reading and Writing XML Files ADO.NET can convert data from data source into XML files
Uses methods WriteXml, ReadXml andGetXml
35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ' Fig. 19.30 XMLWriter.vb ' Demonstrates generating XML from an ADO.NET DataSet Public Class FrmXMLWriter Inherits System.Windows.Forms.Form ' constructor Public Sub New() MyBase.New()
Outline
XMLWriter.vb
Establishes a connection to the Baseball database InitializeComponent() Method Fill of class OleDbDataAdapter is called to populate with data from the ' Add any initialization after BaseballDataSet the ' InitializeComponent() call Players table in the Baseball database
' open database connection BaseballConnection.Open() Binds the
dgdPlayers to BaseballDataSet to the information to the user with display data from OleDbDataAdapter
Friend WithEvents cmdWrite As System.Windows.Forms.Button Friend WithEvents dgdPlayers As System.Windows.Forms.DataGrid Friend WithEvents txtOutput As System.Windows.Forms.TextBox Friend WithEvents BaseballConnection As _ System.Data.OleDb.OleDbConnection
Friend WithEvents BaseballDataAdapter As _ System.Data.OleDb.OleDbDataAdapter
36
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 Friend WithEvents BaseballDataSet As System.Data.DataSet
Outline
' write XML Private Sub cmdWrite_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdWrite.Click ' write XML representation of DataSet to file BaseballDataSet.WriteXml("Players.xml") ' display XML in TextBox txtOutput.Text &= "Writing the following XML:" & _ vbCrLf & BaseballDataSet.GetXml() & vbCrLf End Sub ' cmWrite_Click End Class ' FrmXMLWriter
DataSet method WriteXml is invoked to generate an XML representation of the data contained in the DataSet XMLWriter.vb representation of DataSet button clicked and then writes the XMLwhen to the specified file
37
38