1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual Basic 2005 Databases phần 10 doc

74 186 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning Visual Basic 2005 Databases phần 10
Trường học University of Information Technology
Chuyên ngành Computer Science
Thể loại Tài liệu
Thành phố Ho Chi Minh City
Định dạng
Số trang 74
Dung lượng 760,64 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Click Timesheet Events in the Class Name combo box; and in the Method Name combo box, choose the Loadevent.Add the following code to the TimeSheet_Loadprocedure: Private Sub TimeSheet_Lo

Trang 1

Private Sub copyToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles copyToolStripButton.Click

EditCopy()End Sub

35. Click the Class Name combo box and choose pasteToolStripButton;and in the Method Namecombo box, choose the Clickevent Add the following code to the pasteToolStripButton_Clickprocedure:

Private Sub pasteToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles pasteToolStripButton.Click

EditPaste()End Sub

36. Click the Class Name combo box and choose UndoToolStripButton;and in the Method Namecombo box, choose the Clickevent Add the following code to the UndoToolStripButton_Clickprocedure:

Private Sub UndoToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles UndoToolStripButton.Click

EditUndo()End Sub

37. Click the Class Name combo box and choose AddToolStripButton;and in the Method Namecombo box, choose the Clickevent Add the following code to the AddToolStripButton_Clickprocedure:

Private Sub AddToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles AddToolStripButton.Click

ActionAdd()End Sub

38. Click the Class Name combo box and choose UpdateToolStripButton;and in the Method Namecombo box, choose the Clickevent Add the following code to the UpdateToolStripButton_Clickprocedure:

Private Sub UpdateToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles UpdateToolStripButton.Click

ActionUpdate()End Sub

39. Click the Class Name combo box and choose DeleteToolStripButton;and in the Method Namecombo box, choose the Clickevent Add the following code to the DeleteToolStripButton_Clickprocedure:

Private Sub DeleteToolStripButton_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles DeleteToolStripButton.Click

ActionDelete()End Sub

Trang 2

This is all of the code that you need to add to the Admin form At this point, you can save and run yourproject and test the menu items and toolbar buttons You’ll be able to exit the application, cut, copy,paste, undo, and select all functions in the text boxes, and display the Help form.

TimeSheet form code

In this section, you add some common code to make the TimeSheet form functional This is not

database-related code, as that code will be added in the appropriate chapters

To add this code:

1. Right-click the TimeSheet form in the Solution Explorer window and choose View Code fromthe context menu

2. Add some variable declarations to the form first These variables will be accessible to all procedures in this form Add the following variables at the top of your class:

Public Class TimeSheet

‘Private variablesPrivate intIndex As Integer

Private blnEmployeeDisplay As Boolean = True

Private strAppTitle As String

3. Get the application title from the executable name and set the current date in the status bar Theform’s Loadprocedure is the ideal place to perform these operations Click (Timesheet Events)

in the Class Name combo box; and in the Method Name combo box, choose the Loadevent.Add the following code to the TimeSheet_Loadprocedure:

Private Sub TimeSheet_Load(ByVal sender As Object, _ByVal e As System.EventArgs) Handles Me.Load

‘Set the current date in the date panel in the status barToolStripDate.Text = Date.Today

‘Get the process title from the executable namestrAppTitle = My.Application.Info.Title

End Sub

4. Now add some code to exit the application Click exitToolStripMenuItem in the Class Namecombo box and the Clickevent in the Method Name combo box Add the following code to theexitToolStripMenuItem_Clickprocedure:

Private Sub exitToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles exitToolStripMenuItem.Click

Me.Close()End Sub

5. Now add some code to navigate from the Managers view to the Employees view Click

MyTimeSheetToolStripMenuItem in the Class Name combo box and the Clickevent in theMethod Name combo box Add the following code to the MyTimeSheetToolStripMenuItem_Clickprocedure:

664

Trang 3

Private Sub MyTimeSheetToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles MyTimeSheetToolStripMenuItem.Click

‘Undock the PanelpnlManager.Dock = DockStyle.None

‘Move it out of the waypnlManager.Location = New Point(5000, 5000)

‘Set the Dock property to Fill

‘(this will cause the location to change to 0,0)pnlEmployee.Dock = DockStyle.Top

‘Set the view flagblnEmployeeDisplay = TrueEnd Sub

6. Add some code to navigate from the Employees view to the Managers view ClickEmployeeTimeSheetsToolStripMenuItem in the Class Name combo box and the Clickevent in the Method Name combo box Add the following code to the

‘Set the Dock property to Fill

‘(this will cause the location to change to 0,0)pnlManager.Dock = DockStyle.Top

‘Set the view flagblnEmployeeDisplay = FalseEnd Sub

7. Finally, add some code to display the About form Click aboutToolStripMenuItem in the ClassName combo box and the Clickevent in the Method Name combo box Add the followingcode to the aboutToolStripMenuItem_Clickprocedure:

Private Sub aboutToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles aboutToolStripMenuItem.Click

Dim objAbout As New AboutobjAbout.ShowDialog(Me)objAbout.Dispose()objAbout = NothingEnd Sub

About form code

In this section, you add some common code to make the About form functional The About form can becalled from both the Admin form and the TimeSheet form

Trang 4

To add this code:

1. Right-click the About form in the Solution Explorer window and choose View Code from thecontext menu

2. Set the Textproperty of the various labels on the About form when the form loads Click theClass Name combo box and choose (About Events); and in the Method Name combo box,choose the Loadevent Add the following code to the About_Loadprocedure:

Private Sub About_Load(ByVal sender As Object, _ByVal e As System.EventArgs) Handles Me.Load

‘Set this form’s Text property by using the

‘Text property of the parent formMe.Text = “About “ & Owner.Text

‘Set the application icon using the parent form’s icon imgApplicationIcon.Image = Owner.Icon.ToBitmap()

‘Get a reference to the AssemblyInfo for this applicationDim objAssemblyInfo As Type = sender.GetType()

‘Set the Text property for the title, version, copyright

‘and description labelslblTitle.Text = My.Application.Info.TitlelblVersion.Text = My.Application.Info.Version.ToStringlblCopyright.Text = My.Application.Info.CopyrightlblDescription.Text = My.Application.Info.DescriptionEnd Sub

That’s all the code that you need for this project at this time You can test the code for the About form byrunning your project and choosing the About menu item from the Help menu When your About form isdisplayed, you see the information that was read from your Assembly, and it should look similar to theform shown in Figure B-10

Figure B-10

666

Trang 5

After adding the list box to your form, you switch to the Code Editor for Form1and then add thefollowing Importsstatements:

Imports System.DataImports System.Data.OleDb

Public Class Form1

In the Loadevent for the form, you should have code similar to the code shown here to populatethe list box:

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

‘Declare variables and objectsDim strConnectionString As String = _

“SELECT FirstName, LastName FROM Employees”

Dim objCommand As New OleDbCommand(strSQL, objConnection)Dim objDataAdapter As New OleDbDataAdapter(objCommand)Dim objDataTable As New Data.DataTable(“Employees”)

Trang 6

Dim objDataRow As DataRow

NextCatch OleDbExceptionErr As OleDbException

‘Write the exceptionDebug.WriteLine(OleDbExceptionErr.Message)Catch InvalidOperationExceptionErr As InvalidOperationException

‘Write the exceptionDebug.WriteLine(InvalidOperationExceptionErr.Message)End Try

‘Close the database connectionobjConnection.Close()

‘Clean upobjDataRow = NothingobjDataTable.Dispose()objDataTable = NothingobjDataAdapter.Dispose()objDataAdapter = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = NothingEnd Sub

Exercise 2 solution

The code created for this exercise should look very similar to the last Try It Out in this chapter, except thatinstead of using a DataTableand DataAdapterobject, you use just a DataReaderobject and populatethe list box on your form using the DataReaderobject

The code in the Loadevent of your form should look similar to the code shown here and your formresults should look identical to those shown in Figure 2-3

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

‘Declare variables and objectsDim strConnectionString As String = _

“Provider=Microsoft.Jet.OLEDB.4.0;” & _

“Data Source=C:\Program Files\Microsoft Office\Office11\” & _

668

Trang 7

Dim objConnection As New OleDbConnection(strConnectionString)Dim strSQL As String = _

“SELECT FirstName, LastName FROM Employees”

Dim objCommand As New OleDbCommand(strSQL, objConnection)Dim objReader As OleDbDataReader

‘Write the exceptionDebug.WriteLine(OleDbExceptionErr.Message)Catch InvalidOperationExceptionErr As InvalidOperationException

‘Write the exceptionDebug.WriteLine(InvalidOperationExceptionErr.Message)End Try

‘Close the DataReader objectobjReader.Close()

‘Close the database connectionobjConnection.Close()

‘Clean upobjReader.Dispose()objReader = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = NothingEnd Sub

Chapter 3

Exercise 1 solution

After configuring your data source for the DataGridView control, your DataGridView control will bebound to the ProductsBindingSourcecomponent, which is automatically generated YourDataGridView control will also contain columns for ProductName, UnitPrice, UnitsInStock, andUnitsOnOrder When you run your project, the DataGridView control is populated with the data fromthese fields in your database

Trang 8

Exercise 2 solution

After adding your labels and text boxes to your form, you should click the Textproperty of the

DataBindingsproperty to configure your data source as you did in the “Binding Data to TextBoxControls” Try It Out exercise in this chapter After your data source is configured, you set the Textproperty of the DataBindingsproperty of each of the text boxes using the appropriate fields in theSuppliersBindingSourcecomponent, which was automatically added to your project Finally, youadd a BindingNavigator control to your form and set the BindingSourceproperty to the

SuppliersBindingSourcecomponent

Chapter 4

Exercise 1 solution

The SELECTstatement for your query should look like the example shown here:

SELECT ProjectName, SequenceNumber

SET ProjectDescription = @ProjectDescription

WHERE ProjectID = @ProjectID;

“Data Source=C:\Chapter 5\ProjectTimeTracker.mdb;”

Private objConnection As OleDbConnectionPrivate objCommand As OleDbCommandPrivate objDataAdapter As OleDbDataAdapterPrivate objDataTable As DataTable

670

Trang 9

The code to load the combo box could be placed in the Form Loadevent or in a button Clickevent andshould look similar to this:

‘Initialize the Connection objectobjConnection = New OleDbConnection(strConnectionString)

‘Initialize the Command objectobjCommand = New OleDbCommand(“SELECT ProjectID, ProjectName “ & _

“FROM Projects”, objConnection)

‘Initialize the DataAdapter object and set the SelectCommand propertyobjDataAdapter = New OleDbDataAdapter

ComboBox1.ValueMember = “ProjectID”

‘Clean upobjDataAdapter.Dispose()objDataAdapter = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = Nothing

ComboBox1.ValueMember = “ProjectID”

‘Turn off the loading flagblnIsLoading = False

Trang 10

The code you added to the ComboBox1_SelectedValueChangedevent handler should look similar tothe code shown here:

Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, _ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged

‘Exit if the combo box is being loaded

If blnIsLoading ThenExit Sub

End If

‘Initialize the Connection object and open itobjConnection = New OleDbConnection(strConnectionString)objConnection.Open()

‘Initialize the Command objectobjCommand = New OleDbCommand

‘Set the objCommand object propertiesobjCommand.CommandText = “usp_SelectProject”

objCommand.CommandType = CommandType.StoredProcedureobjCommand.Connection = objConnection

‘Add the required parameter for the queryobjCommand.Parameters.Add(“@ProjectID”, OleDbType.Guid, 16).Value = _New Guid(ComboBox1.SelectedValue.ToString)

‘Execute the QueryobjDataReader = objCommand.ExecuteReader()

‘If we have data then display the project description

If objDataReader.HasRows ThenobjDataReader.Read()TextBox1.Text = objDataReader.Item(“ProjectDescription”)End If

‘Close the DataReader and ConnectionobjDataReader.Close()

objConnection.Close()

‘Clean upobjDataReader = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = NothingEnd Sub

672

Trang 11

Chapter 6

Exercise 1 solution

The first thing that you do after adding your controls is create your application configuration settingsand then set a reference to the System.Datanamespace Then you should add the following Importsstatements:

Imports System.DataImports System.Data.OleDb

In the Clickevent for the button, the first thing you do is declare and initialize a Connectionobjectusing the configuration settings that you specified

‘Declare and initialize a Connection objectDim objConnection As New OleDbConnection( _

“Provider=” & My.Settings.Provider & “;” & _

“Data Source=” & My.Settings.DataSource & “;”)

Next, you use the same code from the btnDataReader_Clickprocedure from the Access SQL projectadding the necessary code to open and close the database connection

‘Declare and initialize a new instance of the OleDbCommand classDim objCommand As New OleDbCommand(TextBox1.Text, objConnection)

‘Declare an OleDbDataReader objectDim objDataReader As OleDbDataReader

‘Declare a String variableDim strData As String

‘Remove the last comma from the string

Trang 12

‘CleanupobjCommand.Dispose()objCommand = NothingobjDataReader = NothingobjConnection.Dispose()objConnection = NothingEnd Sub

When you run your project, enter a SQL statement, and click the button, you should receive results ofthat query listed in the text box on the form

Chapter 7

Exercise 1 solution

Your queries should look similar to the following

Query to select all scores:

SELECT ScoreID, Opposition, OurScore, TheirScore, DatePlayed

FROM Scores

ORDER BY DatePlayed;

Query to select a specific score:

SELECT ScoreID, Opposition, OurScore, TheirScore, DatePlayed

FROM Scores

WHERE ScoreID = @ScoreID;

Query to insert a score:

INSERT INTO Scores (ScoreID, Opposition, OurScore, TheirScore, DatePlayed)

VALUES (@ScoreID,@Opposition, @OurScore, @TheirScore, @DatePlayed);

674

Trang 13

Query to update a score:

UPDATE Scores SET Opposition = @Opposition, OurScore = @OurScore,

TheirScore = @TheirScore, DatePlayed = @DatePlayedWHERE ScoreID = @ScoreID;

Query to delete a score:

DELETEFROM ScoresWHERE ScoreID = @ScoreID;

Exercise 2 solution

The first thing that you should do after designing your form is add a reference to the System.Datanamespace Then you should add the following Importsstatement at the top of your Formclass:Imports System.Data.OleDb

Public Class Form1

The private variables needed in your form include:

‘Private variables and objectsPrivate intRowsAffected As Integer

Private strConnection As String

Private objConnection As OleDbConnectionPrivate objCommand As OleDbCommandPrivate objDataReader As OleDbDataReader

Next, you should add three private procedures: one to open the database connection, one to close thedatabase connection, and one to load the scores list

Private Sub OpenConnection()Try

objConnection.Open()Catch OleDbExceptionErr As OleDbExceptionThrow New System.Exception(OleDbExceptionErr.Message, _OleDbExceptionErr.InnerException)

Catch InvalidOperationExceptionErr As InvalidOperationExceptionThrow New System.Exception(InvalidOperationExceptionErr.Message, _InvalidOperationExceptionErr.InnerException)

End TryEnd Sub

Private Sub CloseConnection()objConnection.Close()

Trang 14

End Sub

Private Sub LoadScores()

‘Declare variablesDim objListViewItem As ListViewItem

Try

‘Initialize the Command object and set its propertiesobjCommand = New OleDbCommand(“usp_SelectScores”, objConnection)objCommand.CommandType = Data.CommandType.StoredProcedure

‘Open the database connectionOpenConnection()

‘Get the dataobjDataReader = objCommand.ExecuteReader

‘See if any data exists before continuing

‘Add the sub items to the listview itemobjListViewItem.SubItems.Add( _

objDataReader.Item(“OurScore”))objListViewItem.SubItems.Add( _objDataReader.Item(“TheirScore”))objListViewItem.SubItems.Add( _Format(objDataReader.Item(“DatePlayed”), “g”))

‘Add the ListViewItem to the ListView controllvwScores.Items.Add(objListViewItem)

Trang 15

MessageBox.Show(OleDbExceptionErr.Message)End Try

End Sub

The form’s Loadand Closingevents are ideal places to put your code to initialize your Connectionobject and to perform the final cleanup of your resources These procedures should contain code similar

to the code shown here:

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

‘Build the SQL connection string and initialize the Connection objectobjConnection = New OleDbConnection( _

“Provider=Microsoft.Jet.OLEDB.4.0;” & _

“Data Source= \ \ProjectTimeTracker.mdb;”)

‘Load the scoresLoadScores()End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, _ByVal e As System.Windows.Forms.FormClosingEventArgs) _Handles Me.FormClosing

‘Clean up

If Not objDataReader Is Nothing ThenobjDataReader.Close()

objDataReader = NothingEnd If

If Not Command() Is Nothing ThenobjCommand.Dispose()

objCommand = NothingEnd If

If Not objConnection Is Nothing ThenobjConnection.Close()

objConnection.Dispose()objConnection = NothingEnd If

‘Add the Parameter to the Parameters collectionobjCommand.Parameters.Add(“@ScoreID”, OleDbType.Guid, 16).Value = _

Trang 16

objDataReader.Item(“Opposition”)txtOurScore.Text = _

objDataReader.Item(“OurScore”)txtTheirScore.Text = _

objDataReader.Item(“TheirScore”)txtDatePlayed.Text = _

End Sub

The code for your Add, Update, and Delete buttons is shown here:

Private Sub btnAdd_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles btnAdd.Click

Try

‘Initialize the Command object and set its propertiesobjCommand = New OleDbCommand(“usp_InsertScore”, objConnection)objCommand.CommandType = Data.CommandType.StoredProcedure

‘Add the Parameters to the Parameters collectionobjCommand.Parameters.Add(“@ScoreID”, _

OleDbType.Guid, 16).Value = Guid.NewGuid()objCommand.Parameters.Add(“@Opposition”, _OleDbType.VarChar, 50).Value = txtOpposition.TextobjCommand.Parameters.Add(“@OurScore”, _

678

Trang 17

OleDbType.UnsignedTinyInt, 1).Value = _CType(txtOurScore.Text, Byte)

objCommand.Parameters.Add(“@TheirScore”, _OleDbType.UnsignedTinyInt, 1).Value = _CType(txtTheirScore.Text, Byte)

objCommand.Parameters.Add(“@DatePlayed”, _OleDbType.DBDate, 8).Value = _

‘Clear the input fieldstxtScoreID.Text = String.EmptytxtOpposition.Text = String.EmptytxtOurScore.Text = String.EmptytxtTheirScore.Text = String.EmptytxtDatePlayed.Text = String.Empty

‘Reload the Scores listLoadScores()

Catch OleDbExceptionErr As OleDbExceptionMessageBox.Show(OleDbExceptionErr.Message)End Try

‘Add the Parameters to the Parameters collectionobjCommand.Parameters.Add(“@Opposition”, _OleDbType.VarChar, 50).Value = txtOpposition.TextobjCommand.Parameters.Add(“@OurScore”, _

OleDbType.UnsignedTinyInt, 1).Value = _CType(txtOurScore.Text, Byte)

objCommand.Parameters.Add(“@TheirScore”, _OleDbType.UnsignedTinyInt, 1).Value = _CType(txtTheirScore.Text, Byte)

Trang 18

objCommand.Parameters.Add(“@DatePlayed”, _OleDbType.DBDate, 8).Value = _

CType(txtDatePlayed.Text, DateTime)objCommand.Parameters.Add(“@ScoreID”, _OleDbType.Guid, 16).Value = _New Guid(txtScoreID.Text)

‘Open the database connectionOpenConnection()

‘Execute the queryintRowsAffected = objCommand.ExecuteNonQuery()

‘Close the database connectionCloseConnection()

‘Check the rows affected

If intRowsAffected = 0 ThenThrow New Exception(“Update Score Failed”)End If

‘Clear the input fieldstxtScoreID.Text = String.EmptytxtOpposition.Text = String.EmptytxtOurScore.Text = String.EmptytxtTheirScore.Text = String.EmptytxtDatePlayed.Text = String.Empty

‘Reload the Scores listLoadScores()

Catch OleDbExceptionErr As OleDbExceptionMessageBox.Show(OleDbExceptionErr.Message)End Try

‘Add the Parameter to the Parameters collectionobjCommand.Parameters.Add(“@ScoreID”, _

OleDbType.Guid, 16).Value = _New Guid(txtScoreID.Text)

‘Open the database connectionOpenConnection()

‘Execute the queryintRowsAffected = objCommand.ExecuteNonQuery()

‘Close the database connection

680

Trang 19

‘Check the rows affected

If intRowsAffected = 0 ThenThrow New Exception(“Delete Score Failed”)End If

‘Clear the input fieldstxtScoreID.Text = String.EmptytxtOpposition.Text = String.EmptytxtOurScore.Text = String.EmptytxtTheirScore.Text = String.EmptytxtDatePlayed.Text = String.Empty

‘Reload the Scores listLoadScores()

Catch OleDbExceptionErr As OleDbExceptionMessageBox.Show(OleDbExceptionErr.Message)End Try

Next, in your Form Loadevent, you add code similar to the code that follows There are two Usingstatements shown, with the first being commented out The first Usingstatement is the one that you usefor connecting to SQL Server and you replace the parameters with values that are specific to your environment The second Usingstatement is used for connecting to Oracle and again you replace theparameters with values that are specific to your environment:

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

‘SQL Server connection

‘Using objData As New WDABase(“SQL Server”, “OracleSql”, _

‘ “ProjectTimeTracker”, “thearon”, “thearon”)

‘Oracle connectionUsing objData As New WDABase(“Oracle”, “wrox”, _

Trang 20

ListBox1.ValueMember = “ProjectID”

‘Close the database connectionobjData.CloseConnection()

Catch ExceptionErr As Exception

‘Display the errorMessageBox.Show(ExceptionErr.Message)End Try

End UsingEnd Sub

Exercise 2 solution

You add code to the Clickevent of the list box and it should look similar to the code shown here Thefirst Usingstatement is the one that you use for connecting to SQL Server and you replace the parameterswith values that are specific to your environment The second Usingstatement is used for connecting toOracle and again you replace the parameters with values that are specific to your environment:

Private Sub ListBox1_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles ListBox1.Click

‘SQL Server connection

‘Using objData As New WDABase(“SQL Server”, “OracleSql”, _

‘ “ProjectTimeTracker”, “thearon”, “thearon”)

‘Oracle connectionUsing objData As New WDABase(“Oracle”, “wrox”, _

Trang 21

‘Close the DataReaderobjData.DataReader.Close()

‘Close the database connectionobjData.CloseConnection()

End If

Catch ExceptionErr As Exception

‘Display the errorMessageBox.Show(ExceptionErr.Message)End Try

End UsingEnd Sub

Trang 22

After designing your form, you should set a reference to the System.Datanamespace Readers usingOracle should also set a reference to the System.Data.OracleClientnamespace Next, you right-clickthe project in the Solution Explorer and choose Add ➪ Existing Item from the context menu You thenadd the app.configfile and the WDABaseclass from your Time Tracker application.

The app.configfile needs to be modified directly so you should view the code by double-clicking theapp.configfile in the Solution Explorer Next, you rename all instances of Time_Trackerto

Exercise_1

For your application to recognize the new settings that were imported, you need to view the Propertypages for your application by right-clicking the project in the Solution Explorer and choosing Propertiesfrom the context menu Then you click the Settings tab in the Property Pages and Visual Studio 2005 displays a dialog box informing you that new settings were imported from the app.configfile At thispoint, you save your project to save the changes

Next, you import the System.Data namespace in Form1:

Imports System.Data

You add your code to populate the list box to the form’s Loadevent Optionally, you can add a button toyour form and put the code in the button’s Clickevent Your code to execute the view and load the listbox should look similar to the code shown here:

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

‘Initialize a new instance of the data access base classUsing objData As New WDABase

‘Bind ListBox controlListBox1.DataSource = objDataTableListBox1.DisplayMember = “ProjectName”

ListBox1.ValueMember = “ProjectID”

Catch ExceptionErr As ExceptionMessageBox.Show(ExceptionErr.Message, “Exercise 1”)End Try

End UsingEnd Sub

684

Trang 23

Exercise 2 solution

The exercise requires you to add a text box to your form and code to the list box’s Clickevent Yourcode should look similar to the code shown here:

SQL Server and Oracle

Private Sub ListBox1_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles ListBox1.Click

‘Initialize a new instance of the data access base classUsing objData As New WDABase

Try

SQL Server

‘Build the SQL stringobjData.SQL = “SELECT ProjectDescription “ & _

“FROM vw_SelectProjects “ & _

“WHERE ProjectID = @ProjectID”

‘Initialize the Command objectobjData.InitializeCommand()

‘Add a Parameter to the Parameters collectionobjData.AddParameter(“@ProjectID”, _

Data.SqlDbType.UniqueIdentifier, 16, ListBox1.SelectedValue)

Oracle

‘Build the SQL stringobjData.SQL = “SELECT ProjectDescription “ & _

“FROM vw_SelectProjects “ & _

“WHERE ProjectID = :inProjectID”

‘Initialize the Command objectobjData.InitializeCommand()

‘Add a Parameter to the Parameters collectionobjData.AddParameter(“inProjectID”, _

Data.OracleClient.OracleType.Char, 36, ListBox1.SelectedValue)

SQL Server and Oracle

‘Open the connectionobjData.OpenConnection()

‘Get the data in a DataReader objectobjData.DataReader = objData.Command.ExecuteReader

‘See if any data exists before continuing

If objData.DataReader.HasRows Then

‘Read the first row

Trang 24

‘Populate the fields on the formtxtProjectDescription.Text = _objData.DataReader.Item(“ProjectDescription”)

End UsingEnd Sub

Next, you delete the WDABaseclass from your project as it is no longer needed

The following variable declarations are needed at the top of your form class:

‘Private variables and objectsPrivate strCompany As String = “Wrox”

Private strApplication As String = “Time Tracker”

Private objProjects As WroxBusinessLogic.WBLProjects

Private objDataSet As Data.DataSetPrivate objProjectsDS As Data.DataSet

Next, you modify the procedure to load the list box to use the GetProjectsmethod in the businesslogic component Your code for this procedure should now look similar to the code shown here:

‘Initialize a new instance of the business logic componentUsing objProjects As New WroxBusinessLogic.WBLProjects( _strCompany, strApplication)

Trang 25

ListBox1.DataSource = objProjectsDS.Tables(“Projects”)ListBox1.DisplayMember = “ProjectName”

ListBox1.ValueMember = “ProjectID”

Catch ExceptionErr As ExceptionMessageBox.Show(ExceptionErr.Message, “Exercise 1”)End Try

“ProjectDescription”)

Catch ExceptionErr As ExceptionMessageBox.Show(ExceptionErr.Message, “Exercise 1”)End Try

“ProjectDescription”) = String.Empty Then

txtProjectDescription.Text = “No Data Available”

ElsetxtProjectDescription.Text = _objDataSet.Tables(“Project”).Rows(0).Item( _

“ProjectDescription”)End If

Trang 26

IF EXISTS (SELECT Ranking FROM Roles WHERE Ranking = @Ranking)

BEGINRAISERROR(‘Ranking already exists and cannot be duplicated’,18,1)END

ELSE

BEGINBEGIN TRYINSERT INTO Roles(RoleID, RoleName, RoleDescription, Ranking, LastUpdateDate)VALUES(@RoleID, @RoleName, @RoleDescription, @Ranking, GETDATE())END TRY

BEGIN CATCHRAISERROR(‘Insert into Roles failed.’,18,1)END CATCH

WHERE Ranking = inRanking;

RAISE_APPLICATION_ERROR (-20999,

‘Ranking already exists and cannot be duplicated’);

EXCEPTIONWHEN NO_DATA_FOUND THENBEGIN

INSERT INTO Roles(RoleID, RoleName, RoleDescription, Ranking, LastUpdateDate)

688

Trang 27

VALUES(inRoleID, inRoleName, inRoleDescription, inRanking, SYSDATE);EXCEPTION

WHEN OTHERS THENRAISE_APPLICATION_ERROR( -20999,’Insert into Roles failed.’);

TYPE CURSOR_TYPE IS REF CURSOR;

PROCEDURE usp_Chapter12Ex1 (results_cursor OUT CURSOR_TYPE);

JOIN Roles ON Users.RoleID = Roles.RoleIDORDER BY UserName;

Trang 28

‘Set the DataGridView propertiesDataGridView1.AlternatingRowsDefaultCellStyle.BackColor = _Color.WhiteSmoke

‘Create and add DataGridView text box columnsDim objColumn As New DataGridViewTextBoxColumnWith objColumn

.HeaderText = “User Name”

.DataPropertyName = “UserName”

.Width = 200End With

DataGridView1.Columns.Add(objColumn)

objColumn = New DataGridViewTextBoxColumn690

Trang 29

With objColumn.HeaderText = “Role Name”

.DataPropertyName = “RoleName”

.Width = 100End With

DataGridView1.Columns.Add(objColumn)

‘Clean upobjDataAdapter.Dispose()objDataAdapter = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = NothingobjDataSet.Dispose()objDataSet = NothingCatch SqlExceptionErr As SqlExceptionMessageBox.Show(SqlExceptionErr.Message)End Try

“Data Source=Wrox;” & _

“User ID=thearon;” & _

‘Set the DataGridView properties

Trang 30

DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = _Color.WhiteSmoke

‘Create and add DataGridView text box columnsDim objColumn As New DataGridViewTextBoxColumnWith objColumn

.HeaderText = “User Name”

.DataPropertyName = “UserName”

.Width = 200End With

DataGridView1.Columns.Add(objColumn)

‘Clean upobjDataAdapter.Dispose()objDataAdapter = NothingobjCommand.Dispose()objCommand = NothingobjConnection.Dispose()objConnection = NothingobjDataSet.Dispose()objDataSet = NothingCatch OracleExceptionErr As OracleExceptionMessageBox.Show(OracleExceptionErr.Message)End Try

AS

BEGIN TRY

DELETE FROM ROlesWHERE RoleID = @RoleIDEND TRY

BEGIN CATCH

BEGIN

692

Trang 31

RAISERROR(‘Delete role failed.’,18,1)RETURN

ENDEND CATCH

Oracle

CREATE OR REPLACE PROCEDURE usp_DeleteRole(

inRoleID CHAR)

AS

BEGINDELETE FROM RolesWHERE RoleID = inRoleID;

EXCEPTIONWHEN OTHERS THENRAISE_APPLICATION_ERROR( -20999,’Delete role failed.’);

AS

BEGIN TRYDELETE FROM UsersWHERE UserID = @UserIDEND TRY

BEGIN CATCHBEGINRAISERROR(‘Delete user failed.’,18,1)RETURN

ENDEND CATCH

Oracle

CREATE OR REPLACE PROCEDURE usp_DeleteUser(

inUserID CHAR)

AS

BEGINDELETE FROM UsersWHERE UserID = inUserID;

EXCEPTION

Trang 32

WHEN OTHERS THENRAISE_APPLICATION_ERROR( -20999,’Delete user failed.’);

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

The DeleteUserfunction in your WDAUsersclass in your data access component should look similar tothe following code:

Trang 33

MyBase.AddParameter(“@UserID”, _SqlDbType.UniqueIdentifier, 16, UserID)

‘Execute the stored procedureDeleteUser = ExecuteStoredProcedure()Catch ExceptionErr As Exception

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

The DeleteRolefunction in the WBLRolesclass in your business logic component should look similar

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

Finally, the DeleteUserfunction in the WBLUsersclass in your business logic component should looksimilar to this code:

Public Function DeleteUser(ByVal UserID As Guid) As BooleanTry

‘Call the data component to delete the userReturn objWDAUsers.DeleteUser(UserID)Catch ExceptionErr As Exception

Throw New System.Exception(ExceptionErr.Message, _ExceptionErr.InnerException)

End TryEnd Function

Trang 34

‘Delete the role

If Not objRoles.DeleteRole( _New Guid(txtRoleID.Text)) ThenThrow New Exception(“Delete Role Failed”)End If

End Using

‘Clear the input fieldstxtRoleID.Text = String.EmptytxtRoleName.Text = String.EmptytxtRoleDescription.Text = String.EmptytxtRanking.Text = String.Empty

‘Delete the user

If Not objUsers.DeleteUser( _New Guid(txtUserID.Text)) ThenThrow New Exception(“Delete User Failed”)End If

End Using

‘Clear the input fieldstxtUserID.Text = String.EmptytxtLogin.Text = String.EmptytxtPassword.Text = String.EmptytxtFirstName.Text = String.EmptytxtLastName.Text = String.EmptytxtEmail.Text = String.EmptytxtPhone.Text = String.EmptyoptStatusActive.Checked = TruetxtUserUpdateDate.Text = String.Empty

‘Reload the Managers combo boxCall LoadManagers()

‘Reload the Users listCall LoadUsers()cboUserGroup.SelectedIndex = -1cboUserRole.SelectedIndex = -1cboUserManager.SelectedIndex = -1696

Trang 35

Index

Trang 37

= (equal sign), 558/ (forward slash), 591() (parentheses), 557

% (percent sign), 387

|| (pipe characters), 367, 386, 419+ (plus sign)

SQL Server concatenation, 367, 386, 419URL, concatenating, 591

deleting project, 127–128, 129, 134–135described, 2

disposing of objects, 130dynamic connectionsbuilding, 157–158Close button and cleanup, 167connection string, building, 74data wizards, drawbacks to, 73error handling, 166

opening, closing, and checking connectionstate, 75–81

parameters, 164–165utility, 159–164variables, 165errors, handling, 129group table queriesbinding, 149–150building, 136–139database connection, opening, 150–151deleting, 144

error handling, 147, 150, 151filling, 147–148

filling with updates, 153–154initializing Command object, 152–153inserting, 142–143

loading, 139–142, 146–147parameters, adding, 153previous list of items, clearing, 148–149testing, 144–146

updating, 143In-Line SQLdescribed, 81

Ngày đăng: 12/08/2014, 10:21

TỪ KHÓA LIÊN QUAN