You are on page 1of 27

1

VB.NET

UNIT 4 For

III-CSE

2002 Prentice Hall. All rights reserved.

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

DelegateBubbleSo Declaration of a delegate Comparator rt.vb

' sort array depending on comparator Public Sub SortArray(ByVal array As Integer(), _ ByVal Compare As Comparator)
Dim i, pass As Integer

Returns value Boolean

Define method SortArray

For pass = 0 To array.GetUpperBound(0)

' comparison inner loop For i = 0 To array.GetUpperBound(0) - 1


If Compare(array(i), array(i + 1)) Then Swap(array(i), array(i + 1)) End If Next ' inner loop Next ' outer loop End Sub ' SortArray ' swap two elements Private Sub Swap(ByRef firstElement As Integer, _ ByRef secondElement As Integer)

Determines how to sort the array

2002 Prentice Hall.


All rights reserved.

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

2002 Prentice Hall.


All rights reserved.

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

Displays a list of sorted sequence


' TextBox that contains original list Friend WithEvents txtOriginal As TextBox Friend WithEvents lblOriginal As Label ' TextBox that contains sorted list Friend WithEvents txtSorted As TextBox Friend WithEvents lblSorted As Label ' Buttons for creating and sorting lists Friend WithEvents cmdCreate As Button Friend WithEvents cmdSortAscending As Button Friend WithEvents cmdSortDescending As Button ' Windows Form Designer generate code

Creates a list in either ascending or descending order

' reference to object containing delegate Dim mBubbleSort As New CDelegateBubbleSort()

' 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

Defines method SortAscending 2002 Prentice Hall.


All rights reserved.

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

Defines method SortDescending

' 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

2002 Prentice Hall.


All rights reserved.

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)

Methods cmdSortAscending_Click and

2002 Prentice Hall.


All rights reserved.

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

2002 Prentice Hall.


All rights reserved.

10

Outline
FrmBubbleSort.vb

2002 Prentice Hall.


All rights reserved.

11

Outline
FrmBubbleSort.vb

2002 Prentice Hall.


All rights reserved.

12

2. Event-Handling Model Event handler


Method called by event Receives event information

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

2002 Prentice Hall. All rights reserved.

13

12.3 Event-Handling Model

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.

Event-handling model using delegates.

14

12.3 Event-Handling Model

Fig. 12.6
2002 Prentice Hall. All rights reserved.

Events section of the Properties window.

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

Beginning of Visual Studio generated code

' This call is required by the Windows Form Designer. InitializeComponent()

' 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

Friend WithEvents lblOutput As System.Windows.Forms.Label

2002 Prentice Hall.


All rights reserved.

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

Visual Studio generated code


2002 Prentice Hall.
All rights reserved.

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

SimpleEvenExampl e.vb Reference to the object that generated the event

Name of the handler llowed by an underscore and the event name

Event arguments object

Event-handling code displays a message box

2002 Prentice Hall.


All rights reserved.

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

2002 Prentice Hall. All rights reserved.

30
295 296 297 298 299 300 301 302 Me.ResumeLayout(False) End Sub ' InitializeComponent #End Region End Class ' FrmTableDisplay

Outline
DisplayTable.vb

2002 Prentice Hall.


All rights reserved.

31

19.6.2 Querying the Books Database Use SELECT statements on database and display results

2002 Prentice Hall. All rights reserved.

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()

2002 Prentice Hall.


All rights reserved.

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

2002 Prentice Hall.


All rights reserved.

34

19.8 Reading and Writing XML Files ADO.NET can convert data from data source into XML files
Uses methods WriteXml, ReadXml andGetXml

2002 Prentice Hall. All rights reserved.

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

' This call is required by the Windows Form Designer.

' fill DataSet BaseballDataAdapter.Fill(BaseballDataSet, "Players")

dgdPlayers to BaseballDataSet to the information to the user with display data from OleDbDataAdapter

' bind DataGrid to DataSet dgdPlayers.SetDataBinding(BaseballDataSet, "Players") End Sub

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

2002 Prentice Hall.


All rights reserved.

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

' Visual Studio .NET generated code

' 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

2002 Prentice Hall.


All rights reserved.

37

19.8 Reading and Writing XML Documents


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version="1.0" standalone="yes"?> <NewDataSet> <Players> <firstName>John</firstName> <lastName>Doe</lastName> <battingAverage>0.375</battingAverage> <playerID>1</playerID> </Players> <Players> <firstName>Jack</firstName> <lastName>Smith</lastName> <battingAverage>0.223</battingAverage> <playerID>2</playerID> </Players> <Players> <firstName>George</firstName> <lastName>O'Malley</lastName> <battingAverage>0.444</battingAverage> <playerID>3</playerID> </Players> </NewDataSet>

Fig. 19.31 XML document generated from DataSet in DatabaseXMLWriter.

2002 Prentice Hall. All rights reserved.

38

.NET DATA PROVIDERS

2002 Prentice Hall. All rights reserved.

You might also like