Vous êtes sur la page 1sur 138

Summary Total OCR 2 Lesson 14: Objectives Getting Started JAM 14.D.1 14.P.

1 Events and Delegates Summary Total Cycle8 OCR 1 Lesson 15: Objectives Getting Started JAM 15.D.1 15.D.2 Using Web Services in a Web Application Summary Total

10 105 5 20 5 30 30 20 5 115

5 15 2 30 30 15 8 12 115 2 45 2 20 15 5 5 10 104

OCR 2

Lesson 16: Objectives Getting Started JAM 16.D.1 Deploying Components JAM Deploying Web Services Summary Total

138 Programming in Visual Basic .NET-Coordinator Guide

NIIT

JAM 9.D.1 9.D.2 9.P.1 Creating a Graphical Interface 9.D.3 9.D.4 JAM Summary Total OCR 2 Lesson 10: Objectives Getting Started JAM 10.D.1 Threads in Visual Basic .NET JAM Summary Total Cycle6 OCR 1 Lesson 11: Objectives 11.D.1 11.P.1 11.D.2 11.D.3 11.D.4 Summary Total OCR 2 Lesson 12: Objectives 12.D.1 12.D.2 12.D.3 12.P.1 Summary Total Cycle7 OCR 1 Lesson 13: Objectives Getting Started 13.D.1 13.P.1
NIIT

2 25 15 20 5 15 15 2 5 116 5 25 5 30 30 10 10 115

5 25 15 15 20 20 10 110 5 30 20 20 30 10 115 5 30 30 30

Programming in Visual Basic .NET-Coordinator Guide 137

Common Dialog Classes JAM Summary Total Cycle3 OCR 1 Lesson 5 : Objectives Getting Started 5.D.1 5.P.1 Summary Total OCR 2 Lesson 6: Objectives 6.D.1 6.D.2 6.D.3 6.D.4 Summary Total Cycle4 OCR 1 Lesson 7: Objectives 7.D.1 Maintaining Data Concurrency 7.P.1 Summary Total OCR 2 Lesson 8: Objectives Getting Started 8.D.1 8.D.2 8.P.1 8.D.3 Summary Total Cycle5 OCR 1 Lesson 9: Objectives Getting Started
136 Programming in Visual Basic .NET-Coordinator Guide

25 5 5 117

5 30 50 15 10 110 5 15 30 15 30 10 105

5 45 20 30 10 110 5 5 20 20 25 20 10 105

2 10
NIIT

SESSION PLAN
Cycle # Cycle1 OCR 1 Lesson 1: Objectives Getting Started .NET Framework JAM Introduction to Visual Basic .NET Visual Studio .NET IDE Summary Total OCR 2 Lesson 2: Objectives Getting Started Visual Basic .NET Language Features JAM 2.D.1 JAM 2.P.1 Summary Total Cycle2 OCR 1 Lesson 3: Objectives Getting Started 3.D.1 3.D.2 3.P.1 JAM Summary Total OCR 2 Lesson 4: Objectives Getting Started 4.D.1 4.P.1 JAM 5 20 30 20 25 2 5 107 2 30 20 25 5 5 15 15 5 10 45 10 105 5 15 30 5 20 5 20 10 110 Activity/Problem No. Duration (In Mins)

NIIT

Programming in Visual Basic .NET-Coordinator Guide 135

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim result As Integer Dim sr As SoccerRanker = New SoccerRanker() sr.PlayerPosition = TextPosition.Text sr.NormalGoalsFor = TextNGoalsFor.Text sr.NormalGoalsAgainst = TextNGoalsAgainst.Text sr.PenaltyGoalsFor = TextPGoalsFor.Text sr.PenaltyGoalsAgainst = TextPGoalsAgainst.Text If sr.PlayerPosition = "MidFielder" Then sr.ShotsTaken = TextShotTaken.Text End If result = sr.CalculatePoints() MsgBox("The total number of points is " & result) End Sub Private Sub TextPosition_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextPosition.LostFocus If Not (TextPosition.Text = "GoalKeeper" Or TextPosition.Text = "MidFielder" Or TextPosition.Text = "Forward") Then MsgBox("Position should be either of GoalKeeper, MidFielder, or Forward (Case Sensitive)") End If End Sub End Class

134 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Public Property ShotsTaken() As Integer Get Return shottaken End Get Set(ByVal Value As Integer) shottaken = Value End Set End Property Public Function CalculatePoints() As Double Select Case playposition Case Is = "GoalKeeper" tpoints = (ngoalsfor * 3 + 4 * pgoalsfor) (ngoalsagainst + pgoalsagainst) Return tpoints Case Is = "MidFielder" tpoints = (ngoalsfor * 2) + shottaken Return tpoints Case Is = "Forward" tpoints = (ngoalsfor * 4 + pgoalsfor * 3) (ngoalsagainst + pgoalsagainst) Return tpoints End Select End Function End Class

Q2. Solution: Design a user control and add text boxes and buttons to it. Add the component already created to calculate the number of points earned by a player. Here we have assumed the namespace ( name of the project if no namespace has been specified) to be SoccerLib. Imports SoccerLib Public Class MyUserControl Inherits System.Windows.Forms.UserControl

NIIT

Programming in Visual Basic .NET-Coordinator Guide 133

End Property Public Property PenaltyGoalsAgainst() As Integer Get Return pgoalsagainst End Get Set(ByVal Value As Integer) pgoalsagainst = Value End Set End Property Public Property NormalGoalsAgainst() As Integer Get Return ngoalsagainst End Get Set(ByVal Value As Integer) ngoalsagainst = Value End Set End Property Public Property PlayerPosition() As String Get Return playposition End Get Set(ByVal Value As String) playposition = Value End Set End Property Public ReadOnly Property TotalPoints() As String Get Return tpoints End Get End Property

132 Programming in Visual Basic .NET-Coordinator Guide

NIIT

SOLUTIONS : ADDITIONAL EXERCISES


Q1. Solution: Create a new project and add a component to it. Change the name of the component class to SoccerRanker. Add the code as given to the component class. Public Class SoccerRanker Inherits System.ComponentModel.Component Private pgoalsfor As Integer Private ngoalsfor As Integer Private pgoalsagainst As Integer Private ngoalsagainst As Integer Private playposition As String Private tpoints As Double Private shottaken As Integer Public Property PenaltyGoalsFor() As Integer Get Return pgoalsfor End Get Set(ByVal Value As Integer) pgoalsfor = Value End Set End Property Public Property NormalGoalsFor() As Integer Get Return ngoalsfor End Get Set(ByVal Value As Integer) ngoalsfor = Value End Set

NIIT

Programming in Visual Basic .NET-Coordinator Guide 131

To be able to use the Web service that contains a Web method for providing details about a query, perform the following steps: 1. 2. Right-click the DisplayCustOrderDet project in the Solution Explorer window and select Add Web Reference from the shortcut menu. This opens the Add Web Reference dialog box. In the Address text box, enter the path of your Web service as shown below: http://localhost/CustOrderData/service1.asmx?WSDL 3. 4. 5. 6. Click the Go To ( ) button.

Click the Add Reference button. On performing this task, Visual Studio .NET will generate the proxy class for the Web service. In the Solution Explorer window, expand the Web References folder. Right-click the localhost folder and select Rename from the shortcut menu. Rename the folder as WebService1. Import the Web service namespace by adding the following code at the top of the code-behind file: Imports DisplayCustOrderDet.WebService1

7.

Type the following code in the WebForm1 class: Private Sub btnGetData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetData.Click Dim WebServiceObj As New CustOrderData() Dim dsQryDet As New DataSet() dsQryDet = WebServiceObj.CustOrder(txtCustID.Text, txtFromDt.Text, txtToDt.Text) dgOrderDet.DataSource = dsQryDet.Tables(0).DefaultView dgOrderDet.DataBind() End Sub

8.

Select Debug Start. In the form set the values of various controls, as given below: Customer ID: C003 From Date: 06/12/2001 To Date: 06/20/2001

9.

Click the Get Data button and check whether the details about orders are displayed in the DataGrid control.

130 Programming in Visual Basic .NET-Coordinator Guide

NIIT

6. 7.

In the Solution Explorer window, select Form1.vb and click the View Code button. Import the Web service namespace by adding the following code at the top of the code-behind file: Imports DispCustOrderDet.WebService1

8.

Type the following code in the Form1 class: Private Sub btnGetData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetData.Click Dim table1 As New DataTable() Dim dsOrderData As New DataSet() Dim WebServiceObj As New CustOrderData() dsOrderData = WebServiceObj.CustOrder(txtCustID.Text, dtFromDt.Value.Date.ToString, dtToDt.Value.Date.ToString) table1 = dsOrderData.Tables(0) dgOrderDet.DataSource = table1.DefaultView End Sub

9.

Select Debug Start. In the form set the values of various controls, as given below: Customer ID: C003 From Date: June 12, 2001 To Date: June 20, 2001

10. Click the Get Data button and check whether the details about orders are displayed in the DataGrid control.

UGP 3
1. Select File New Project. In the New Project dialog box, select Visual Basic Projects from the Project Types pane. Select ASP.NET Web Application from the Templates pane. Specify the name of the project as DisplayCustOrderDet and Click the OK button. In the ToolBox, click the Web Forms tab. Create three Label controls and set their Text property to Customer ID, From Date, and To Date, respectively. Create three TextBox controls and set their ID property to txtCustID, txtFromDt, and txtToDt respectively. Create a Button control. Set its Text property to Get Data and ID property to btnGetData. Create a DataGrid control and set its ID property to dgOrderDet. In the Solution Explorer window, click the Show All Files button. Expand WebForm1.aspx. Double-click WebForm1.aspx.vb to switch to the Code Editor window.

2. 3. 4. 5. 6. 7.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 129

SqlQry = "Select Inv, Date, CustID, Cost, Advance from CustOrder Where CustID = '" + CustID + "' and [Date] Between '" + StartDt + "' and '" + EndDt + "'" Dim CmdObj As New SqlDataAdapter(SqlQry, SqlConStr) Dim DsObj As New DataSet() CmdObj.Fill(DsObj, "ORDERDATA") Return DsObj End Function 6. 7. Save the file. To test the Web service, select Debug Start. This opens the Internet Explorer window. Click the CustOrder link. This opens a new page. Specify the value of the CustID parameter as C003. Specify the value of the StartDt parameter as 06/10/2001 and the value of the EndDt parameter as 06/20/2001. Click the Invoke button. Check whether the Web service returns the order details in an XML format.

UGP 2
1. Select File New Project. In the New Project dialog box, select Visual Basic Projects from the Project Types pane. Select Windows Application from the Templates pane. Change the name of the project to DispCustOrderDet. Create three Label controls in the form and set their Text property to Customer ID, From Date, and To Date, respectively. Create a TextBox control and set its Name property to txtCustID. Create two DateTimePicker controls and set their Name properties to dtFromDt and dtToDt, respectively. Create a Button control and set its Name property to btnGetData. Set the Text property of the control to Get Data. Create a DataGrid control and set the Name property of the control to dgOrderDet.

2. 3. 4. 5. 6.

To be able to use the Web service that contains a Web method for providing details about a query, perform the following steps: 1. 2. Right-click the DispCustOrderDet project in the Solution Explorer window and select Add Web Reference from the shortcut menu. This opens the Add Web Reference dialog box. In the Address text box, enter the path of your Web service as shown below: http://localhost/CustOrderData/service1.asmx?WSDL 3. 4. 5. Click the Go To ( ) button.

Click the Add Reference button. On performing this task, Visual Studio .NET will generate the proxy class for the Web service. In the Solution Explorer window, expand the Web References folder. Right-click the localhost folder and select Rename from the shortcut menu. Rename the folder as WebService1.

128 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Namespace DBCon Public Class GetProdDet Functions for establishing connection

End Class End Namespace List the steps that you will follow to create a single deployable unit containing these two files. Ans: To create a single deployable unit containing the two files, CalcDisc.vb and ProductDet.vb, perform the following steps given: 1) Build the GetProdDet class into a module by using the following statement: vbc /t:module GetProdDet.vb /r:system.dll /r:system.data.dll 2) Compile the CalcDiscountAmt class file by executing the following statement at the command prompt: vbc /addmodule:GetProdDet.netmodule /t:module CalcDisc.vb 3) Create a multi-file assembly by using the Al.exe utility by typing the following statement at the command prompt: al /out:App.dll /t:lib GetProdDet.netmodule CalDisc.netmodule

Solutions: Unguided Practice UGP 1


1. 2. 3. 4. In Visual Studio .NET, select File New Project. Select Visual Basic Projects from the Project Types pane. Select ASP.NET Web Service from the Templates pane. Change the name of the project to CustOrderData and click the OK button. Click the Service1.asmx file in the Solution Explorer window. Click the View Code button in the Solution Explorer window to switch to the Code Editor window. Add the following statements before the class declaration to import the required namespaces: Imports System.Data Imports System.Data.SqlClient 5. Change the name of the Web service class to CustOrderData. Type the following code in the class: <WebMethod()> Public Function CustOrder(ByVal CustID As String, ByVal StartDt As String, ByVal EndDt As String) As DataSet Dim SqlConStr As String SqlConStr = "Server=localhost;database=CallCenter11;uid=sa;pwd=" Dim SqlQry As String

NIIT

Programming in Visual Basic .NET-Coordinator Guide 127

privileges, they will not be able to install an application. However, depending on the availability of time, faculty may allow students to create a deployment project and build the .msi file.

Additional Inputs
Demo
The demo for this lesson is stored in the Solutions\VB.NET\Lesson16 folder. To install the Data Entry Application, double-click the Setup.exe file located in the Solutions\VB.NET\Lesson 16\16.D.1\CallCenter\Debug folder.

Performing Conditional Deployment


You can perform deployment based on some conditions. Conditional deployment can be performed by using either the Launch Condition editor in a deployment project or the Condition property of a file or a registry key. The information about conditional deployment is provided in the Appendix.

Solutions: Just a Minute


1. Which of the following deployment editors can be used to specify the Control Panel settings on the target computer? a) b) c) d) 2. File Systems editor Launch Conditions editor Registry editor User Interface editor

Ans: c) Registry editor Consider the following files: CalcDisc.VB Imports System.Data Imports System.Data.SQL Imports DBCon Public Class CalcDiscountAmt Call functions from the GetProdDet class Calculate the discounted price End Class

ProductDet.VB Imports System.Data Imports System.Data.SQL

126 Programming in Visual Basic .NET-Coordinator Guide

NIIT

4. 5. 6. 7. 8. 9.

In the Address text box, type the address as http://localhost/GetQueryData/service1.asmx?WSDL and press the Enter key. Click the Add Reference button. In the Solution Explorer window, right-click the newly created (localhost) folder, and select Rename from shortcut menu. Type the name of the folder as WebService1. In the Solution Explorer window, select Form1.vb and click the View Code button. Press the Enter key after the Imports statement. Execute the project by selecting Debug Start.

To test the application, specify Q001 as the query ID.

Solutions: Just a Minute


1. What is the difference between a Web service and a component?

Ans: Components use object model-specific protocols, such as Internet Inter-ORB Protocol (IIOP) and Remote Method Invocation (RMI), for communicating with client applications. In contrast to components, Web services use Internet standards, such as HTTP and XML, to communicate with client applications. This communication approach makes Web services independent of any language or platform. Any computer that has access to the Internet can easily access a Web service. This also enables a number of applications residing on a variety of software and hardware platforms to exchange data. Thus, Web services architecture takes the best features of components and combines them with the Web. 2. How can you locate the Web services developed by a Web service provider?

Ans: Web services providers publish the information about their Web services at centralized locations called Web service directories. They provide information about their Web services by publishing the .disco file. This XML-based file contains links to other resources that describe the Web service. You can use the Add Web Reference dialog box to browse such Web directories and locate a Web service that suits your requirements. 3. Which attribute is used to describe a Web service?

Ans: The WebService attribute is used to provide a description about a Web service.

Lesson Sixteen
Experiences
This lesson discusses various project templates included in Visual Studio .NET for creating deployment projects. Discuss each template and explain the situation in which the template will be used. After explaining deployment project templates, demonstrate the use of various deployment editors. Steps for performing various tasks, such as adding files, registry keys, and launch conditions, are given in the book. You can refer to these steps and demonstrate how each editor can be used for different purposes. The demo given in this lesson uses the Data Entry application created in Lesson 9. Therefore, ensure that the application exists on the computer before you start with this lesson. It is important to note that the setup.exe and the .msi files generated in the demo can be executed only by users belonging to the Administrators group. Since students cannot be given administrative

NIIT

Programming in Visual Basic .NET-Coordinator Guide 125

communication protocol for Web services. State that SOAP is an XML-based protocol that runs over HTTP. In other words, SOAP = HTTP + XML. While discussing the demo, state the need for a Web service in the given scenario. Demonstrate each step involved in the creation of a Web service. Discuss the code model for a Web service. Explain the <WebService()> and <WebMethod()> attributes of a Web service. In the next demo, explain the process of locating and using a Web service in an application. In addition, state that the process of locating and using a Web service in an application is the same in case of both Windows- and Web-based applications. This lesson also includes a simple ASP.NET Web application. While discussing this application, discuss some of the commonly used controls in ASP.NET Web application. Demonstrate the use of the design and HTML views of the Web Form Designer. State that the code for application logic can be provided in either the HTML file or the code-behind file.

Additional Inputs
The demos for this lesson are stored in the Solutions\VB.NET\Lesson15\ folder. To be able to work with Web projects, you must have IIS 4.0 or later installed on the computer. In addition, you must be a member of the Administrators or VS Developers group. The instructions for executing demos are given below:

15.D.1
Perform the following steps to create the Web service: 1. 2. 3. 4. 5. Select File New Project. Select Visual Basic Projects from the Project Types pane. Select ASP.NET Web Service from the Templates pane. Specify the location as http://localhost/GetQueryData. Click the OK button. Switch to the Code Editor window by pressing the F7 key. Remove the existing code and paste the code given in the Service1.asmx.vb file provided on the CD. In the code, check value of the SqlConStr variable, which contains the connection string. Change the string as per the requirements. (For example, if the name of the database server is NIIT-CATS, the connection string accordingly.) To execute the Web service, press the F5 key.

7.

To test the Web service, specify the query ID as Q001.

15.D.2
The files for this demo are stored in the Solutions\VB.NET\Lesson 15\15.D.2\DisplayQueryStatus folder. If the project does not work properly (it may give an error when you click the Query button on the form), perform the following steps: 1. 2. 3. Open the project in Visual Studio .NET. In the Solution Explorer window, expand the Web References folder. Delete the WebService1 folder by selecting it and pressing the Del key. Right-click the project (DisplayQueryStatus) in the Solution Explorer window and select Add Web Reference from the shortcut menu to invoke the Add Web Reference dialog box.

124 Programming in Visual Basic .NET-Coordinator Guide

NIIT

10. Add the following code in the Click event of the Button1: Dim ic As CInterestCalculator = New CInterestCalculator() If (Val(txtPrincipal.Text) > 0) Then ic.PrincipalAmount = txtPrincipal.Text End If If (Val(txtTime.Text) > 0) Then ic.NumberOfYears = txtTime.Text End If If (Val(txtRate.Text) > 0) Then ic.InterestRate = txtRate.Text End If Dim interest = ic.CalculateInterest() Dim amount = ic.CalculateAmount() MsgBox("Total interest is " & interest) MsgBox("Total amount is " & amount) 11. Build the application using the Build Solution option from the Build menu.

Note
You can test the InterestCalculationCtl control by performing the following steps: 1. 2. 3. 4. Create a new Windows Application project with the project name as Interest_Calculation_Test. Add the component InterestCalculationCtl to the Toolbox by selecting Customize Toolbox option from the short-cut menu. Drag the InterestCalculationCtl control to Form1. Execute the application.

Lesson Fifteen
Experiences
Begin the session by revising components. Then, state the limitations of various object models, such as COM and CORBA, in case of Web applications. Then, introduce Web services. State that Web services are reusable components. However, they use HTTP and XML for communicating with client applications. Therefore, they can be used from a computer that has an Internet connection. Discuss various Web service enabling technologies. Explain the role of each of these technologies in the development and discovery of a Web service. In addition, discuss the role of SOAP as a standard

NIIT

Programming in Visual Basic .NET-Coordinator Guide 123

End Get End Property Public Function CalculateInterest() As Double interest = (principal * rate * years) / 100 Return interest End Function Public Function CalculateAmount() As Double amount = interest + principal Return amount End Function End Class 4. Build the application using the Build Solution option from the Build menu.

UGP 2
1. 2. 3. Create a new Windows Control Library project with the name Interest_Calculation _Control. Change the class name and the VB file name to InterestCalculationCtl.vb by right-clicking UserControl1.vb and selecting the Rename option from the short-cut menu. Add the component CInterestCalculator to the Toolbox.

Note
To add the component CInterestCalculator, right-click Toolbox and select Customize Toolbox. In the Customize Toolbox dialog box, click the .NET Framework Components tab and then click the Browse button. Navigate to the bin folder under the Interest_Calculation_Component folder and select Interest_Calculation_Component.dll and click the Open button. 4. 5. 6. 7. 8. Add the component CInterestCalculator to InterestCalculationCtl form from the Toolbox.. Add three Label controls and three TextBox controls to the form Form1. The Text property of the Label controls should be Principal, Time, and Rate respectively. Remove the default values of the Text property for all three TextBox controls. Specify the Name property of the TextBox controls as txtPrincipal, txtTime, and txtRate respectively. Add a button to the form. Change the Text property of the button to Calculate. Add the following code as the first line in the Code window:

Imports Interest_Calculation_Component 9. Change the class name InterestCalculationCtl in the code window.

122 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Return rate End If End Get Set(ByVal Value As Double) If (Value >= 0) Then rate = Value End If End Set End Property Public Property PrincipalAmount() As Double Get If (principal > 0) Then Return principal End If End Get Set(ByVal Value As Double) If (Value > 0) Then principal = Value End If End Set End Property Public ReadOnly Property TotalInterestAmount() As Double Get Return interest End Get End Property Public ReadOnly Property TotalAmount() As Double Get Return amount

NIIT

Programming in Visual Basic .NET-Coordinator Guide 121

18. Drag the CategoryValidatorCtl control to Form1. 19. Execute the application.

Solutions: Unguided Practice UGP 1


1. 2. 3. Create a new Class Library project with the name Interest_Calculation_Component. In the Solution Explorer, right-click Class1.vb to change the name to InterestDeterminator.vb by using the Rename option from the short-cut menu. In the code window, delete the original class and change the code as following:

Public Class CInterestCalculator Inherits System.ComponentModel.Component Private years As Double Private rate As Double Private principal As Double Private interest As Double Private amount As Double Public Property NumberOfYears() As Double Get If (years > 0) Then Return years End If End Get Set(ByVal Value As Double) If (Value > 0) Then years = Value End If End Set End Property Public Property InterestRate() As Double Get If (rate > 0) Then

120 Programming in Visual Basic .NET-Coordinator Guide

NIIT

7.

Add the component CategoryDeterminator to the Toolbox.

Note
To add the component CategoryDeterminator, right-click Toolbox and select Customize Toolbox. In the Customize Toolbox dialog box, click the .NET Framework Components tab and then click the Browse button. Navigate to the bin folder under the Category_Calculation_Component folder and select Category_Calculation_Component.dll and click the Open button. 8. 9. Add the component CategoryDeterminator to CategoryValidatorCtl form from the Toolbox. Add three Label controls and three TextBox controls to the form CategoryValidatorCtl. The Text property of the Label controls should be Hours logged, Hours Worked, and Category respectively.

10. Remove the default values of the Text property for all three TextBox controls. Specify the Name property of the TextBox controls as txtHrslogged, txtHrsWorked, and txtCategory respectively. 11. Add a button to the form. Change the Text property of the button to Calculate. 12. Add the following code as the first line in the Code window: Imports Category_Calculation_Component 13. Change the class name CategoryValidatorCtl in the code window. 14. Add the following code in the Click event of the Button1: Dim cd As CategoryDeterminator cd = New CategoryDeterminator() If (Val(txtHrslogged.Text)>0) then cd.HoursLogged = Val(txtHrslogged.Text) End If If (Val(txtHrslogged.Text) > 0) Then cd.HoursWorked = Val(txtHrsWorked.Text) End If txtCategory.Text = cd.CalculateCategory() If (Val(txtHrslogged.Text) < Val(txtHrsWorked.Text)) Then MsgBox("Hours worked cannot be more than Hours logged") End If 15. Build the application using the Build Solution option from the Build menu. 16. Create a new Windows Application project with the project name as Employee_Category_Test. 17. Add the component CategoryValidatorCtl to the Toolbox by selecting Customize Toolbox option from the short-cut menu.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 119

If (hrsworked > 0) Then Return hrsworked End If End Get Set(ByVal Value As Double) hrsworked = Value End Set End Property Public Function CalculateCategory() As String Dim productivity As Integer If (hrsworked > 0 And hrslogged > 0) Then productivity = (hrsworked / hrslogged) * 10 Select Case productivity Case 1 To 3 Return "Average" Case 4 To 6 Return "Good" Case 7 To 10 Return "Excellent" End Select End If If (hrsworked = 0 Or hrslogged = 0) Then Return "Enter Correct Values" End If End Function End Class 4. 5. 6. Build the application using the Build Solution option from the Build menu. Create a new Windows Control Library project with the name Employee_Category _Control. Change the class name and the VB file name to CategoryValidatorCtl.vb by right-clicking UserControl1.vb and selecting the Rename option from the short-cut menu.

118 Programming in Visual Basic .NET-Coordinator Guide

NIIT

4.

Identify the syntactical error in the following code snippet:

Public Class Form1 Inherits System.Windows.Forms.Form Event UserEvent(dim x as Integer) End Class Ans. Remove Dim keyword from the parameter list 5. Fill in the blank:

Ans. In Visual Basic .NET, delegates are reference types based on the System.Delegates class.

Solution: Guided Practice 14.P.1


1. 2. 3. Create a new Class Library project with the name Category_Calculation_Component. In the Solution Explorer, right-click Class1.vb to change the name to CategoryDeterminator.vb by using the Rename option from the short-cut menu. In the code window, delete the original class and change the code as following:

Public Class CategoryDeterminator Inherits System.ComponentModel.Component Private hrslogged As Double Private hrsworked As Double Public Property HoursLogged() As Double Get If (hrslogged > 0) Then Return hrslogged End If End Get Set(ByVal Value As Double) hrslogged = Value End Set End Property Public Property HoursWorked() As Double Get

NIIT

Programming in Visual Basic .NET-Coordinator Guide 117

The following is an example of adding a list control when users clicks a button: Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim lstNewListBox As New ListBox() lstNewListBox.size = New Size(150, 200) lstNewlistBox.Location = New Point(50,50) lstNewListBox.Items.Add(First item) lstNewListBox.Items.Add(Second item) Me.Controls.Add(lstNewListBox) End Sub

FAQs
Q1. Can we add a control at run time? Ans. Yes, you can add a control at run time (Refer to Additional Inputs given in lesson 14). Q2. What is side-by-side deployment? Ans. Side-by-side deployment is the process of deploying two different versions of an assembly. Q3. How can we resize more than one control at the same time? Ans. You can resize more than one control at the same time by selecting the controls together.

Solutions: Just a Minute


1. Which method will you override to render graphical user interface to customized controls?

Ans. The OnPaint() method. 2. What format string will you use to specify a date in the year-month-date format?

Ans. yy-MM-dd 3. How will you ensure that an entire control is redrawn?

Ans. By adding the following code to the constructor of the control: ResizeDraw=True

116 Programming in Visual Basic .NET-Coordinator Guide

NIIT

salary = Value Else MsgBox("Employee salary should be between $3000 to $35000") End If End Set End Property End Class Create a test application by the name Employdetails_com. Add a button and three label controls and three textbox controls. Add the following code to the Click event of the button in the test application. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ed As DataValidator = New DataValidator() ed.EmployeeID = TextEmpId.Text ed.EmployeeAge = Val(TextAge.Text) ed.EmployeeSalary = Val(TextSalary.Text) End Sub

Lesson Fourteen
Experiences
Connect to the last unit of components. Tell students that as all controls in Java are JavaBean classes, similarly all controls are components. Emphasize that controls are components that either have a graphical interface or are used in the user interface. To explain user controls, you can use the example of an application in which users can interact with a database. The screen that the users use to view or change data has many controls. All the controls on the screen can be used as one unit. While teaching the rendering of a graphical interface of a customized control, emphasize upon the fact that the OnPaint() method does not belong to controls only. This method needs to be overridden to draw any component. Tell students that they will never call the OnPaint() method directly in their code.

Additional Input
Adding Controls at Run time
You can add controls to forms at run time. This capability was available in the earlier versions of VB also. However, because Visual Basic .NET is based on object-oriented technology, adding controls becomes even easier.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 115

Return empId End Get Set(ByVal Value As String) If Value.Length > 5 Then MsgBox("Employee ID should be of the form E123") ElseIf Value Like "[E][0-9][0-9][0-9]" Then empId = Value Else MsgBox("Employee ID should be of the form E123") End If End Set End Property Public Property EmployeeAge() As Integer Get Return age End Get Set(ByVal Value As Integer) If Value >= 21 And Value <= 60 Then age = Value Else MsgBox("Employee age can be from 21 to 60 years") End If End Set End Property Public Property EmployeeSalary() As Double Get Return salary End Get Set(ByVal Value As Double) If Value >= 3000 And Value <= 35000 Then

114 Programming in Visual Basic .NET-Coordinator Guide

NIIT

2.

How does Visual Basic .NET prevent DLL Hell?

Ans: To avoid DLL Hell, Visual Basic .NET: 1 Isolates applications 2 Enforces Windows NTs Last Known Good 3 Enforces file versioning 3. What is a version number?

Ans: A version number has four parts: the major build version, the minor build version, the build and the revision. It is used by the runtime to determine whether or not two versions are compatible. The major and minor build numbers are used to perform compatibility check. A change in these two numbers signifies a different version. A change in the build number signifies a small change in the form of a patch or bug fixing.

Solutions: Just a Minute


1. You need to write a program to validate user login. This program will be used across applications. What will you develop the program as and why?

Ans: The program will be developed as a component because then you can use it across applications. 2. Why does an assembly need a shared name?

Ans: An assembly needs a shared name to avoid conflicts with other assemblies in the Global Assembly Cache. 3. How will you use a component?

Ans: You will use a component by its fully qualified name.

Solution: Guided Practice 13.P.1


Public Class DataValidator Inherits System.ComponentModel.Component 'Declare the variable Private empId As String Private age As Integer Private salary As Double 'Declare properties Public Property EmployeeID() As String Get

NIIT

Programming in Visual Basic .NET-Coordinator Guide 113

You can tell students that components that deal with business logic, such as calculating price, fit into the middle tier. The presentation tier involves more of visual components. You can compare components to JavaBeans. You can remind them that they had learned about certain standards regarding the writing of a JavaBean. A similar standard is established by IComponent, and in turn, by the Component class of Visual Basic .NET. While covering COM and ActiveX, do not add more content than what is provided in the lesson. Tell students that COM and ActiveX will not be developed in Visual Basic .NET. Emphasize the fact that the use of COM is allowed in Visual Basic .NET for backward compatibility only. Polymorphism is an important concept that the students know well. Here, emphasize upon implementing interfaces.

FAQs
1. What is DLL Hell?

Ans: It is a situation in which one version of a DLL overwrites another version. DLL Hell is a disadvantage that comes with COM. GUIDs are sometimes altered and registry settings are changed, which renders the application that was using the overwritten DLL unable to execute.

112 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Instead of: custid = lbcustid.SelectedItem() result = dt.Rows.Find(custid) txtfname.Text = dt.Columns(1).ToString txtlname.Text = dt.Columns(2).ToString txtaddress.Text = dt.Columns(3).ToString txtphone.Text = dt.Columns(4).ToString txtmail.Text = dt.Columns(5).ToString 8. Remove the breakpoint by right-clicking the line and selecting Remove Breakpoint from the shortcut menu. Run the application again.

UGP 3
1. 3. Open the application DiscountApp Modify the code for the Click event of the Discounted Price button as follows: Try cost = txtcost.Text discount = txtdiscount.Text result = discount / 100 * cost discount = cost result MsgBox(discount,MsgBoxStyle.Information, "Result") Catch err As System.InvalidCastException MsgBox(" Please enter a numeric value", MsgBoxStyle.OKOnly, "Error") txtcost.Text = "" txtdiscount.Text = "" txtcost.Focus() End Try

Lesson Thirteen
Experiences

NIIT

Programming in Visual Basic .NET-Coordinator Guide 111

27. To associate the created HTML Help file with the HelpProvider control, right-click the HelpProvider1 control from the component tray and select Properties from the shortcut menu. 28. The Help file to be associated with the HelpProvider control is specified using the HelpNamespace property of the HelpProvider control. The HelpNamespace property is present under the Misc category in the Properties window. 29. When the HelpNamespace property is clicked, a button appears to the right in the Properties window. Click the displayed button. 30. In the Open Help File dialog box, select the compiled chm file and click Open. 31. Right-click the CrystalReportViewer control and select Properties from the shortcut menu. 32. Enter Using Main Report Window as the keyword in the HelpKeyword on HelpProvider1 property and select KeywordIndex as the HelpNavigator on HelpProvider1 property. Set the ShowHelp on HelpProvider1 property to True.

UGP 2
1. 2. 3. 4. 5. 6. Open the application CustData. In the Windows Form Designer, double-click the Button1 control. The code for the Click event of Button1 is displayed in the Code Editor window. Right-click the line custid = lbcustid.SelectedItem()in the code. Then, select Insert Breakpoint from the shortcut menu. To run the application, select Debug from the menu bar. Then, select Start from the Debug menu. The application runs till it reaches the breakpoint. Execute the application step-by-step by using Step Into from the Debug menu to check each line of code. Add the following lines: custid = lbcustid.SelectedItem() result = dt.Rows.Find(custid) txtfname.Text = result(1).ToString txtlname.Text = result(2).ToString txtaddress.Text = result(3).ToString txtphone.Text = result(4).ToString txtmail.Text = result(5).ToString

110 Programming in Visual Basic .NET-Coordinator Guide

NIIT

S.No.

HTML Title

Content size<br> Search Text - Used to search for a text in the Crystal Report<br>

To be saved as

12. To create an index file, click the Index tab. A message box is displayed confirming whether to create a new index file or open an existing one. 13. By default, Create a new index file radio button is selected. Click OK. 14. In the Save As dialog box, enter the name and the path for the index file and click Save. 15. To insert a keyword, click the Insert a keyword icon on the toolbar. 16. The Index Entry dialog box is displayed. Type Using Group Tree in the Keyword text box and click the Add button. The Path or URL dialog box is displayed. 15. Click the Browse button and select usinggrouptree.htm from the Open dialog box. Click Open. 16. Click OK. Again click OK to close the Index Entry dialog box. 17. Similarly, insert the following keywords:
Keyword Using Main Report Window Using Report Toolbar File to linked with the keyword usingmainreportwindow.htm usingtoolbar.htm

18. To create a content page, click the Contents tab. A message box is displayed confirming whether to create a new contents file or opening an existing one. Click OK. Enter the path and name for the Contents file as tocforCrystalReportHelp and click Save. 19. Click the Insert a page icon on the toolbar. 20 In the Table of Contents Entry dialog box, type Using Group Tree in the Entry title text box and enter usinggrouptree.htm in the File or URL text box. 21. Similarly, add the following content pages:
Entry title Using Main Report Window Using Report Toolbar File to linked with the title usingmainreportwindow.htm usingtoolbar.htm

22. You can specify a default HTML file for your project. When the Help file is displayed to a user, the HTML file set as the default file for the project is opened and displayed automatically. To set a default file for the project, click the Project tab and then click the Change project options icon from the toolbar. 23. Enter the file usingmainreportwindow.htm as the default file in the Default file combo box and click OK. 24. Compile the Project file. 25. Open the application project and open the form designer. 26. Drag a HelpProvider control to the form.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 109

7. 8. 9.

To create a new HTML page, click File from the menu bar and then click New from the File menu. Select HTML File in the New dialog box and click OK. Enter the title for the HTML page as Using the group tree and click OK.

10. Write the following text after the <Body> tag in the HTML source page in the right side of the window and save the HTML page as usinggrouptree.htm. Group tree is used to display the groups into which the Crystal Report is divided. For example, if the Crystal Report is grouped to display data on a weekly basis, the Group Tree would contain the weeks into which the Crystal Report has been broken down.<br> To view the data for a group, click that group in the Group Tree.<br> The data for the group is outlined with a red line. 11. Similarly, create HTML pages as displayed below:
S.No. 1. HTML Title Using the Main Report Window Content The Main Report window is used to display the Crystal Report. The data of the Crystal Report can be viewed in the Main Report window.<br> This window displays: Field names<br> Field values<br> Page header<br> Report header<br> Page footer<br> Report footer<br> The various toolbar icons of the Report view are:<br> Go to First Page - Used to move to the first page of the Crystal Report<br> Go to Previous Page - Used to move to the previous page of the Crystal Report<br> Go to Next Page- Used to move to the next page of the Crystal Report<br> Go to Last Page - Used to move to the last page of the Crystal Report<br> Goto Page- Used to move to the page specified by the user<br> Close Current View - Used to close the currently open Crystal Report view <br> Print Report - Used to print the Crystal Report<br> Refresh - Used to refresh the Crystal Report view<br> Export Report - Used to export the Crystal Report to other formats, such as Adobe Acrobat, Microsoft Excel, Microsoft Rich Text, HTML, and Microsoft Word<br> Toggle Group Tree - Used to toggle the state of the Group Tree to the opposite of the current state. For example, if the Group Tree is visible in the Crystal Report, clicking the Toggle Group Tree hides the Group Tree, and if the Group Tree is hidden, clicking the Toggle Group Tree icon performs the opposite action<br> Zoom - Used to display the Crystal Report in a customized To be saved as usingmainreportwindow.htm

2.

Using the Crystal Report Toolbar

usingtoolbar.htm

108 Programming in Visual Basic .NET-Coordinator Guide

NIIT

6. 7. 8.

In the Properties window of the ToolBar control, click the ImageList property and then select ImageList1 from the drop-down list. Click the Buttons property and then click the button that appears to the right of the Properties window. The ToolBarButton Collection Editor is displayed. To add a button in the ToolBar control, click the Add button. ToolBarButton1 is added in the Members list. 1. 2. 3. Click the ImageIndex property of ToolBarButton1 to represent the button as an image. From the drop-down list, select 0. The image displayed next to the index number is the image of the button. Set the Text property of ToolBarButton1 as blank.

9. 10.

Similarly, add two more buttons to the toolbar and add images for them and click OK to close the ToolBarButton Collection Editor. Add the following code for the Load event of the form: Dim response As MsgBoxResult response = MsgBox("Do you want to view tool tips for the toolbar icons", MsgBoxStyle.YesNo, "Information") If response = MsgBoxResult.Yes Then ToolBarButton1.ToolTipText = "Save" ToolBarButton2.ToolTipText = "Open" ToolBarButton3.ToolTipText = "New" End If

11.

Execute the application

Solution: Unguided Practice UGP 1


Use the application created for 8.D.1. 1. 2. 3. 4. 5. 6. Open HTML Help Workshop. To create a Project file, click File from the menu bar. Then, click New. The Project option is selected by default. Click OK. The first screen of the wizard for creating a new project is displayed. Click Next. The New ProjectDestination screen is displayed. On this screen, enter the name for the project and the path where you want to create the project as c:\CrystalReportHelp. Click Next. The New ProjectExisting Files screen is displayed. Since you do not have any existing help files, click Next. The New ProjectFinish screen is displayed. Click Finish to create a new Project file.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 107

Lesson Twelve
Experiences
This session contains more practice than theory. Start the session by explaining a scenario in which a new user might need help while working with an application. The user might need to know about how to perform an action or information about an application component, such as buttons and icons. The students should clearly understand the function of a HelpProvider control and its properties. All the three demos use the same Windows application. Therefore, before starting 12.D.2 and 12.D.3, ask the students to remove the HelpProvider control and all other setting added while doing the previous demos.

Solutions: Just A Minute


1. Ans: Identify the methods for providing dynamic help to a user while executing an application. Types of help that can be provided to a user are:


2.

HTML Help ToolTips Whats This Help

Write a code to set the tool tip text for the button control Button1 and display the tool tip text after 1000 milliseconds after the user points to the button and display the tool tip for 2000 milliseconds when the cursor is kept stationary on the button. The code is as follows: ToolTip1.AutoPopDelay = 2000 ToolTip1.InitialDelay = 1000

Ans:

Solution: Guided Practice 12.P.1


Use the application created for 7.P.1. 1. 2. 3. 4. Drag an ImageList control from the Windows Forms tab of the Toolbox into the form. Open the Properties window of the ImageList control. Click the Images property. Then, click the button that appears on the right of the Properties window. The Image Collection Editor is displayed. To add an image in the image list, click the Add button. The Open dialog box is displayed. Select the image file that you want to insert in the image list and click Open. Add three images for the Save, New, and Open buttons and click OK to close the Image Collection Editor dialog box. Drag a ToolBar control from the Windows Forms tab of the Toolbox into the form.

5.

106 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Debugging options can be accessed by expanding the Debugging folder:

Solution: Guided Practice 11.P.1


Use the application created for Lesson 8 Unguided Practice 1. Modify the code for the Click event of the Show Revenue Report button: Try CrystalReportViewer1.ReportSource = "C:\Documents and Settings\User1\My Documents\Visual Studio Projects\WindowsApplication29\Crystalreport1.rpt" Catch err As ApplicationException MsgBox("The Report could not be loaded", MsgBoxStyle.OKOnly, "dxf") End Try Modify the code for the Click event of the Show Employee Performance Report button: Try CrystalReportViewer1.ReportSource = "C:\Documents and Settings\User1\My Documents\Visual Studio Projects\WindowsApplication29\Crystalreport2.rpt" Catch err As ApplicationException MsgBox("The Report could not be loaded", MsgBoxStyle.OKOnly, "dxf") End Try

NIIT

Programming in Visual Basic .NET-Coordinator Guide 105

FAQs
1. Can we view the list of breakpoints that we have in an application?

Ans: Yes. Click Debug from the menu bar. Then, click Windows from the Debug menu and click Breakpoints from the Windows submenu. A list of inserted breakpoints is displayed. 2. How can we jump from one breakpoint to another?

Ans: You can jump to another breakpoint by just double-clicking the other breakpoint. 3. While executing a code, can we ignore the code in the Try block?

Ans: Yes. You can use the Exit Try statement to ignore the code in the Try block.

Solutions: Just A Minute


1. In the TryCatchFinally statement, when is the code given in each of the blocks executed?

Ans: When an application runs, the code in the Try block is executed. If the code in the Try block gives an error, the Catch block handles the error. The code included in the Finally block is executed just before the control exits the TryCatchFinally block in which the error occurred. 2. What is the difference between the On Error GoTo 0, On Error Resume Next, and On Error GoTo ErrorHandler statements and when is each of then used?

Ans: You can use the On Error Resume Next statement to specify that when an error occurs, the control should pass to the next line of code following the line in which the error occurred. The On Error GoTo 0 statement can be used to disable any error handler in a procedure.

Additional Inputs
Debugger settings can be specified by using the Tools menu and selecting Options from the Tools menu. The following dialog box is displayed:

104 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Additional Inputs
The solutions for demos and guided practices for this lesson are stored in the Solutions\VB.NET\Lesson11 folder.

Demos and Practices


Before executing the demos and practices, perform the following steps:

11.D.1
1. Open the Code Editor window of the form. In the code for the Load event of the form: Dim connparameter As String = "provider=sqloledb;user id=sa;password=;database=CallCenter11;server=localhost" 2. Replace the user id, password and server values according to the requirements.

11.D.2
11.D.2 involves ADO.NET connectivity. Therefore, before running the application, perform the steps given for Lesson 5 demos and practices.

11.D.3
1. Open the Code Editor window of the form. In the code for the Load event of the form: Dim connparameter As String = "provider=sqloledb;user id=sa;password=;server=tulikas-d190;" & "Database=" & db 2. Replace the user id, password and server values according to the requirements.

11.D.4
11.D.4 involves ADO.NET connectivity. Therefore, before running the application, perform the steps given for Lesson 5 demos and practices.

11.P.1
Before running 11.P.1, perform the following steps: 1. 2. 3. Copy the project folder to the local machine. Open the Code Editor window for the form. Change the code for the Click event of both the buttons to: CrystalReportViewer1.ReportSource =<path of the crystal report file eg. C:\My Documents\8.D.1\CrystalReport1.rpt>

NIIT

Programming in Visual Basic .NET-Coordinator Guide 103

SalaryObject.ThreadDone MsgBox("The Annual Salary is: " & totalsalary) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Call Callthread() End Sub End Class Public Class SalaryClass Public month As Double Public salary As Double Public totalsalary As Double Public Event ThreadDone(ByVal value As Double) Sub CalculateAnnualSalary() totalsalary = month * salary RaiseEvent ThreadDone(totalsalary) End Sub End Class

Lesson Eleven
Experiences
Start the session with a discussion on the types of errors that can occur in an application. Give examples of syntactical, logical, and run-time errors. Bring out the advantage of structured exception handling by explaining to students that structured exception handling allows filtering of errors based on the error type, error class, error message, and so on. Tell students that including the Finally statement is not necessary for using structured exception handling. Explain that all error classes are derived from the Exception class. Discuss only ApplicationException, SystemException, and IOException classes at this stage. Demonstrate the use of Debug windows to students.

102 Programming in Visual Basic .NET-Coordinator Guide

NIIT

End Sub Private Sub cmdWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWrite.Click sw.BaseStream.Seek(0, SeekOrigin.End) writedata(rtbCQuery.Text, sw) input = MsgBox("Do you wish to read from the file?", MsgBoxStyle.YesNo, "User Input") If input = MsgBoxResult.Yes Then cmdRead.Enabled = True cmdWrite.Enabled = False rtbCQuery.Text = "" End If End Sub Private Sub frmQueryDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdRead.Enabled = False End Sub End Class

10.A.2
Imports System.Threading.Thread Public Class Form1 Inherits System.Windows.Forms.Form Dim WithEvents SalaryObject As New SalaryClass() Protected Sub Callthread() Dim MyThread As New System.Threading.Thread(AddressOf SalaryObject.CalculateAnnualSalary) SalaryObject.month = 12 SalaryObject.salary = 15000 MyThread.Start() End Sub Sub SalaryDoneEventHandler(ByVal totalsalary As Double) Handles

NIIT

Programming in Visual Basic .NET-Coordinator Guide 101

Solutions: Additional Exercises 10.A.1


Imports System.IO Public Class frmQueryDetails Inherits System.Windows.Forms.Form Dim fstream As New FileStream("C:\Customer_Query.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite) Dim sw As New StreamWriter(fstream) Dim input As String Public Sub writedata(ByVal Data As String, ByVal sw As StreamWriter) sw.Write("Entry : " + Today) sw.WriteLine(" sw.Flush() End Sub Public Sub readdata(ByVal r As StreamReader) While r.Peek() > -1 rtbCQuery.Text = r.ReadToEnd End While End Sub Private Sub cmdRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRead.Click Dim sr As New StreamReader(fstream) sr.BaseStream.Seek(0, SeekOrigin.Begin) readdata(sr) cmdWrite.Enabled = True cmdRead.Enabled = False input = MsgBox("Do you wish to clear the text from the text area?", MsgBoxStyle.YesNo, "User Input") If input = MsgBoxResult.Yes Then rtbCQuery.Text = "" End If " + Data)

100 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False Case 1 Dim NewMDIChild As New frmOrderdetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() StatusBar1.ShowPanels = True msg = "Order Details Form. You can use this form to enter the details of an order place by a customer." StatusBarPanel1.Text = msg mnuorder.Enabled = False MenuItem1.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False

Case 2 Dim NewMDIChild As New frmEmployeeDetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() StatusBar1.ShowPanels = True msg = "Employee Details Form. You can use this form to enter the details of an Employee." StatusBarPanel1.Text = msg mnuemployee.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Select End Sub End Class

NIIT

Programming in Visual Basic .NET-Coordinator Guide 99

NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuorder.Enabled = False MenuItem1.Enabled = False StatusBar1.ShowPanels = True msg = "Order Details Form. You can use this form to enter the details of an order place by a customer." StatusBarPanel1.Text = msg Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click End End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ToolBar1.ImageList = ImageList1 tbCustomer.ImageIndex = 0 tbOrder.ImageIndex = 1 tbExit.ImageIndex = 2 End Sub Private Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick Select Case ToolBar1.Buttons.IndexOf(e.Button) Case 0 Dim NewMDIChild As New frmCustomerdetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() StatusBar1.ShowPanels = True msg = "Customer Details Form. You can use this form to enter the details of a Customer." StatusBarPanel1.Text = msg mnucustomer.Enabled = False

98 Programming in Visual Basic .NET-Coordinator Guide

NIIT

NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuemployee.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnudailysales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnudailysales.Click StatusBar1.ShowPanels = True msg = "You have clicked the Daily Sales Report menu option." StatusBarPanel1.Text = msg MsgBox("The Daily Sales Report menu has been clicked") End Sub Private Sub mnuexit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuexit.Click End End Sub Private Sub mnuprint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuprint.Click StatusBar1.ShowPanels = True msg = " You have clicked the Print menu option." StatusBarPanel1.Text = msg pdlg.Document = PDocument Dim result As DialogResult = pdlg.ShowDialog() If result = Windows.Forms.DialogResult.OK Then PDocument.Print() End If End Sub Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Dim NewMDIChild As New frmOrderdetails()

NIIT

Programming in Visual Basic .NET-Coordinator Guide 97

'Create a new instance of frmCustomerdetails Dim NewMDIChild As New frmCustomerdetails() 'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() mnucustomer.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnuorder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuorder.Click StatusBar1.ShowPanels = True msg = "Order Details Form. You can use this form to enter the details of an order place by a customer." StatusBarPanel1.Text = msg Dim NewMDIChild As New frmOrderdetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuorder.Enabled = False MenuItem1.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnuemployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuemployee.Click StatusBar1.ShowPanels = True msg = "Employee Details Form. You can use this form to enter the details of an Employee." StatusBarPanel1.Text = msg Dim NewMDIChild As New frmEmployeeDetails()

96 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Add the following line in the Dispose() method of the frmEmployeedetails: Form1.ActiveForm.Menu.MenuItems(0).MenuItems(2).Enabled = True If Form1.ActiveForm.Menu.MenuItems(0).MenuItems(0).Enabled <> False And Form1.ActiveForm.Menu.MenuItems(0).MenuItems(1).Enabled <> False Then Form1.ActiveForm.Menu.MenuItems(3).Enabled = True Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = True End If Add the following lines in the Dispose() method of the frmOrderdetails: Form1.ActiveForm.Menu.MenuItems(0).MenuItems(1).Enabled = True Form1.ActiveForm.ContextMenu.MenuItems(0).Enabled = True If Form1.ActiveForm.Menu.MenuItems(0).MenuItems(0).Enabled <> False And Form1.ActiveForm.Menu.MenuItems(0).MenuItems(2).Enabled <> False Then Form1.ActiveForm.Menu.MenuItems(3).Enabled = True Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = True End If

UGP 2
Imports System.Drawing.Printing Public Class Form1 Inherits System.Windows.Forms.Form Dim pdlg As New PrintDialog() Friend WithEvents PDocument As New PrintDocument() Dim msg As String Private Sub mnucustomer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnucustomer.Click StatusBar1.ShowPanels = True msg = "Customer Details Form. You can use this form to enter the details of a Customer." StatusBarPanel1.Text = msg

NIIT

Programming in Visual Basic .NET-Coordinator Guide 95

Private Sub mnuprint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuprint.Click pdlg.Document = PDocument Dim result As DialogResult = pdlg.ShowDialog() If result = Windows.Forms.DialogResult.OK Then PDocument.Print() End If End Sub Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Dim NewMDIChild As New frmOrderdetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuorder.Enabled = False MenuItem1.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click End End Sub End Class Add the following line in the Dispose() method of the frmCustomerdetails: Form1.ActiveForm.Menu.MenuItems(0).MenuItems(0).Enabled = True If Form1.ActiveForm.Menu.MenuItems(0).MenuItems(1).Enabled <> False And Form1.ActiveForm.Menu.MenuItems(0).MenuItems(2).Enabled <> False Then Form1.ActiveForm.Menu.MenuItems(3).Enabled = True Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = True End If

94 Programming in Visual Basic .NET-Coordinator Guide

NIIT

mnucustomer.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnuorder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuorder.Click Dim NewMDIChild As New frmOrderdetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuorder.Enabled = False MenuItem1.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnuemployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuemployee.Click Dim NewMDIChild As New frmEmployeeDetails() NewMDIChild.MdiParent = Me NewMDIChild.Show() mnuemployee.Enabled = False Form1.ActiveForm.ContextMenu.MenuItems(1).Enabled = False Form1.ActiveForm.Menu.MenuItems(3).Enabled = False End Sub Private Sub mnudailysales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnudailysales.Click MsgBox("The Daily Sales Report menu has been clicked") End Sub Private Sub mnuexit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuexit.Click End End Sub

NIIT

Programming in Visual Basic .NET-Coordinator Guide 93

cmdRead.Enabled = False cmdWrite.Enabled = True End Sub Private Sub cmdReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReset.Click rtbPDetails.Text = "" End Sub Private Sub frmProductDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdRead.Enabled = False End Sub End Class Save the project by selecting the Save All option from the File menu. 1. 2. Select the Start option from the Debug menu, or press F5. Enter the product details and use the Write Data and Read Data buttons to validate the file I/O operations. Use the Reset button to reset the contents of the RichTextBox control.

Solutions: Unguided Practice UGP 1


Imports System.Drawing.Printing Public Class Form1 Inherits System.Windows.Forms.Form Dim pdlg As New PrintDialog() Friend WithEvents PDocument As New PrintDocument() Private Sub mnucustomer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnucustomer.Click 'Create a new instance of frmCustomerdetails Dim NewMDIChild As New frmCustomerdetails() 'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show()

92 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Write the following code in the Code Editor window of the frmProductDetails form: Public Class frmProductDetails Inherits System.Windows.Forms.Form Private Sub cmdWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWrite.Click FileOpen(1, "c:\Product Details.TXT", OpenMode.Append) ' Open or create file. PrintLine(1, rtbPDetails.Text) 'Write line in the file PrintLine(1) 'Insert a blank line after the first line FileClose(1) ' Close the file cmdRead.Enabled = True cmdWrite.Enabled = False rtbPDetails.Text = "" End Sub Private Sub cmdRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRead.Click Dim TextLine As String FileOpen(1, "c:\Product Details.TXT", OpenMode.Input) ' Open file to read data from it. While Not EOF(1) ' Loop until end of file. ' Read line into variable.

TextLine = LineInput(1)

If rtbPDetails.Text = "" Then rtbPDetails.Text = rtbPDetails.Text + TextLine ' Print to the RichTextBox. Else rtbPDetails.Text = rtbPDetails.Text + Chr(13) + TextLine ' Print to the RichTextBox. End If End While FileClose(1) ' Close the file

NIIT

Programming in Visual Basic .NET-Coordinator Guide 91

You should also have another button to reset the contents of RichTextBox. To indicate the purpose of project, you should name the project as PDetails and set the Name and Text properties of the form as frmProductDetails and Product Details, respectively. The details of the controls that you need to add to the form are given in the following table:
Object Label RichTextBox Button Button Button Text Product details Form Type Product Details Here Read Data Write Data Reset Data lblCaption rtbPDetails cmdRead cmdWrite cmdReset Name

As per the above plan, you need to add a RichTextBox control, a label control, and two buttons, Read Data and Write Data, to the form named frmProductDetails. You also need to add another button, Reset, to reset the contents of RichTextBox. The Read Data button should be used to read data from the existing file Product Details.txt, and the Write Data button should be used to write data to the Product Details.txt file. To ensure that data is first written and then read from the file, initially the Read Data button will be disabled. To design the form, perform the following steps: 1. 2. 3. 4. 5. 6. 7. 8. 9. Start Microsoft Visual Studio .NET using the Start menu. Select the Project option from the New submenu under the File menu. Ensure that in the New Project dialog box, the Project Types is Visual Basic Projects and the Template is Windows Application. Type PDetails in the Name text box and click the OK button. Right-click the Form1.vb form name in the Solution Explorer window and select the Properties option to display the Properties window. Click the form in the design viewer and set the Name and Text properties of the form in the Properties window, as planned. Right-click the PDetails project name and select the Properties option. Select frmProductDetails as the startup object from the Startup object drop-down list and click the OK button. Add the required controls from the Toolbox and name them, as planned, using the Properties window. Organize the controls.

You will use the FileOpen() function to open Product Details.Txt file or create the file, if it does not exist, so that users at the call centers of Diaz Telecommunications are able to read data from and write data to the file. Since the C drive is the default drive on all computers, you should also ensure that the Product Details.txt file is always saved in the C drive of a computer.

90 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Protected Sub Callthread() Dim CalcObject As New CalcClass()

CalcObject.breath = 12 CalcObject.length = 12 MyThread.Start() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Call Callthread() End Sub End Class Class CalcClass Public length As Double Public breath As Double Public area As Double Sub CalculateArea() area = length * breath MsgBox("The area End Sub End Class Ans: Type the declaration of the MyThread variable as: Dim MyThread As New System.Threading.Thread(AddressOf CalcObject.CalculateArea) is: " & area)

Solution: Guided Practice


As per the problem statement, the users at the call centers of Diaz Telecommunications should be able to create a text file and save product details in it. In addition, after the file is created, the users should also be able to open the file and read data from it. Since data is to be read form or write to the file as a sequence of characters, you should implement the relevant built-in functions of Visual Basic .NET to sequentially access the file. To ensure user-friendly interface for reading data from and writing data to the Product Details.txt file, you need to plan an appropriate user interface. Since product details could be in multiple lines, you should include a RichTextBox control in place of the usual TextBox control to capture the product details. To describe the use of the RichTextBox control, you should add an appropriate label for it. In addition, to read from and write to the Product Details.txt file, you should add two buttons to the form.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 89

3.

Complete the following code to ensure that the file Product.txt is opened with no share specification.

Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim fstream As New FileStream("C:\ Product.txt") End Sub End Class Ans: Dim fstream As New FileStream("C:\ Product.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None) 4. Complete the following code to display the contents of the file named Product.txt in the output window.

Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim len As Integer FileOpen(1, "C:\Emp_File.txt", OpenMode.Input) MsgBox(len) FileClose(1) End Sub End Class Ans: Include the line len = LOF(1)before the Msgbox function. 5. There is a class called CalcClass, which has a sub procedure called CalculateArea(). You need to execute this procedure in a separate thread. To execute the CalculateArea () procedure, you need to declare a variable of the thread type. Complete the declaration of the variable in the following code snippet.

Imports System.Threading.Thread Public Class Form1 Inherits System.Windows.Forms.Form

88 Programming in Visual Basic .NET-Coordinator Guide

NIIT

2.

What is a scripting library and how is it used for files?

Ans: A scripting library is used in previous versions of Visual Basic. This library is used to render object-oriented aspects of file handling. 3. When should I use a thread?

Ans: You should use threads when your application:

Has long computational processes Communicates over the Internet Accesses data Uses Microsoft Message Queue Services Performs process control

Solutions: Just a Minute


1. The following code snippet generates a build error. Identify the error. Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim files As FileStream = New FileStream("c:\Product.txt", FileMode.OpenOrCreate) Dim bw As BinaryWriter = New BinaryWriter(files) Dim br As BinaryReader = New BinaryReader(files) Dim j, k As Integer For j = 3 To 9 bw.Write(CStr(j)) Next br.BaseStream.Seek(0, SeekOrigin.Begin) TextBox1.Text = br.ReadChars(14) End Sub End Class Ans: You need to import the System.IO namespace using the Imports statement. 2. What is the difference between the CreateNew and Create constants of the FileMode enumeration? Public Class Form1

Ans: Both Create and CreateNew constants are used to specify that the operating system create a new file. However, if the file already exists, the Create constant will overwrite the file, whereas the CreateNew constant will throw an exception.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 87

Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click End End Sub Save the project by selecting the Save All option from the File menu. 7. Check the application by executing it. 1. 2. 3. 4. Select the Start option from the Debug menu, or press F5. Open the Customer Details, Order Details, Query Details, and Employee Details forms using the respective menus. Display the message by clicking the Daily Sales Report menu. Terminate the application using the Exit menu.

Lesson Ten
Experiences
Start this lesson by asking questions about streams and files. Then, help them connect their existing knowledge about streams and files with the concept of files and streams in Visual Basic .NET. You can simply list the different types of files and streams explained in the lesson and state how to use them. Encourage students to learn about other files on their own. Threading is a concept that students learned in Semester one. However, it is a complex topic, therefore, you should explain it again. While explaining the concepts, use as many examples as possible. You can use the examples given in the Examples and Analogies section. Create a connect with the concepts learned in earlier semesters, but dont assume that students will know the topic thoroughly. It is very important for students to understand that the main method itself is a thread. Tell them that even if they do not create a thread in an application, a primary thread exists. While discussing SyncLock, list its benefits, such as locking, and disadvantages, such as slowdown of the system. Connect SyncLock with the synchronization of code in Java.

Examples and Analogies


You can give the classic example of MS-Word printing a document as well as editing texts. You can also give a day-to-day example such as of three persons who are building a house. Each person is a thread. When a wall is being built, one of them will lay bricks and apply mortar while the other one will prepare the mortar. At the same time, the third person will transfer the mortar and bricks to the person who is actually using them. Each person is involved in a different task but is actually a part of one activity, which is building a wall. Relate this to the working of threads.

FAQs
1. Why should I use SyncLock sparingly?

Ans: SyncLock reduces the overall performance of a system.

86 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Public Sub mnuprint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuprint.Click pdlg.Document = PDocument Dim result As DialogResult = pdlg.ShowDialog() If result = Windows.Forms.DialogResult.OK Then Pdocument.Print() End If End Sub End Class To provide easy access to options, perform the following actions. 1. 2. 3. Click the View Designer button in the Solution Explorer window to display Form1on the screen. Double-click the ContextMenu control in the Toolbox to add the ContextMenu control to Form1. To add menu items to the ContextMenu control, first click the highlighted Context Menu box on the menu bar of the MDI parent form, Form1, and then click the Type Here highlighted box. Type the menu item names as Order and Exit to create two menu options. Invoke the Properties window for the Form1 by right-clicking the Form1.vb label in the Solution Explorer window and selecting the Properties option. Set the ContextMenu property of Form1 to ContextMenu1. This will set the context menu for the MDI parent form, Form1. To ensure that when the context menu items of the Customized Data Entry Application project are clicked, the relevant forms are displayed on the screen, write the code for the Click event of each menu item. The following is the code that you need to write for the Click event of each MenuItem:

4. 5. 6.

Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click 'Create a new instance of frmOrderdetails Dim NewMDIChild As New frmOrderdetails() 'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub

NIIT

Programming in Visual Basic .NET-Coordinator Guide 85

'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub Private Sub mnuorder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuorder.Click 'Create a new instance of frmOrderdetails Dim NewMDIChild As New frmOrderdetails() 'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub Private Sub mnuemployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuemployee.Click 'Create a new instance of frmEmployeedetails Dim NewMDIChild As New frmEmployeedetails() 'Set the parent of the MDI child form. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub Private Sub mnudailysales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnudailysales.Click MsgBox("The Daily Sales Report menu has been clicked") End Sub Private Sub mnuexit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuexit.Click End End Sub

84 Programming in Visual Basic .NET-Coordinator Guide

NIIT

6.

Set the IsMdiContainer property of Form1 to True. This will set the Data Entry Form as the MDI Parent form. Set the WindowState property of Form1 to Maximized. Since Main Form is the MDI Parent form within which all the MDI Child forms are to be displayed, you should display the Main Form in the maximized state. Double-click the MainMenu control in the Toolbox to add the control to the component tray of the project. Add the menu items, as planned. To add menu items in the MainMenu object, click the Type Here box on the menu bar of the MDI Parent form, Form1 and type the menu item name. In Visual Basic .NET, the name that you type is set as the value of the Text property of the menu item.

7.

8. 9.

10. To specify the name for each menu item, as planned, you need to open the Properties window. You can open the Properties window by right-clicking the menu item and selecting the Properties option. After the Properties window is displayed, you should specify the name of the individual menu items, as planned. 11. After you have added the menu items to the MDI Parent form, you need to add the MDI Child forms. To add MDI Child forms, you can either create the data entry forms or reuse the forms that you have created in previous sessions. Since, the data entry forms are already created and are available for reuse, you need to add these forms to the MDI Parent form. To add the existing data entry forms, right-click the Customized Data Entry Application project in the Solution Explorer and select the Add Existing Item option from the Add submenu. 12. In the Add Existing Item dialog box, display the Customer_details folder in which the frmCustomerdetails form is saved. Then, double-click the Customer_details folder to display its contents. Next, select the frmCustomerdetails.vb file from the list of files and click the Open button. If the Customer_details project contains the Customer class in a separate class file, you need to add the Customer.vb file by using the Add Existing Item dialog box. Repeat the step to add the class files and forms for Order, and Employee to Customized Data Entry Application. 13. After all the three forms are added to the Customized Data Entry Application project, write code for each of the menu items added to the project. Write the following code snippets in the Code Editor window of the Customized Data Entry Application MDI form. 14. To ensure that when the submenus of the Forms menu are clicked, the relevant forms are displayed on the screen, write code for the Click event of each menu. The following is the entire code that you need to write: Imports System.Drawing.Printing Public Class Form1 Inherits System.Windows.Forms.Form Dim pdlg As New PrintDialog() Friend WithEvents PDocument As New PrintDocument() Private Sub mnucustomer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnucustomer.Click 'Create a new instance of frmCustomerdetails Dim NewMDIChild As New frmCustomerdetails()

NIIT

Programming in Visual Basic .NET-Coordinator Guide 83

Use menus to allow the users to access the required parts of the application. The menu items identified should be assigned proper names, as given below.
Purpose The Parent Form Customer Details Order Details Employee Details Report Daily Sales Report Invoke Print Dialog Box Quit the application Name mnuforms mnucustomer mnuorder mnuemployee mnureport mnudailysales mnuprint mnuexit &Forms &Customer Details &Order Details &Employee Details &Report & Daily Sales Report &Print &Exit Text 1 2 2 2 1 2 1 1 mnureport mnuforms mnuforms mnuforms Level Grouped Under

The levels specified above indicate the top-level menu and the submenu. The menu items with level 2 are submenus under the relevant groups. The menu items with level 1 are the top-level menus that appear in the menu bar. An MDI form, which will act as a container for the application, will be required. In Visual Basic .NET, you can integrate different parts of an application by implementing menus to the form. The menus can be organized as shown below:

Data Entry Customer Details

Report Daily Sales

Print

Exit

Order Details Employee _Details


To integrate the application, perform the following steps: 1. 2. 3. Start Microsoft Visual Studio .NET using the Start menu. Select the Project option from the New submenu under the File menu. Ensure that in the New Project dialog box, the Project Types is Visual Basic Projects and the Template is Windows Application. Type Customized Data Entry Application in the Name text box and click the OK button. Right-click the Form1.vb form in the Solution Explorer window and select the Properties option to display the Properties window. Specify Main Form as the value for the Text property of the Form1 in the Properties window.

4. 5.

82 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Complete the code for the following Form1_Load Sub procedure to assign appropriate image to each ToolBar button. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ToolBar1.ImageList = ImageList1 End Sub Ans: To assign an appropriate image to each Toolbar button, include the following assignment statements after the ImageList property assignment statement: tbProduct.ImageIndex = 0 tbCustomer.ImageIndex = 1 tbSales.ImageIndex = 2 tbExit.ImageIndex = 3 7. Fill in the blank: The _______ property of StatusBar enables you to specify the message that will be displayed in the StatusBar panel. Ans: text 8. You have added a panel in StatusBar1. How would you ensure that the panel size would be adjusted based on the size of the text it will hold?

Ans: Set the AutoSize property of the panel to Contents.

Solution: Guided Practice 9.P.1


Note: Use the forms Customer, Order, Query, and Employee created in Lesson3 and Lesson4 for this demo. As per the problem statement, you need to integrate three data entry forms. You also need to provide options to access the daily sales report and invoke the Print dialog box. In addition, you need to include an Exit option to the users. To integrate data entry forms and to provide options to access the daily sales report and invoke the Print dialog box, you need to create an MDI application and add menu to the MDI Parent form so that users can switch between the forms and report. The menu should also include an option to invoke the Print dialog box.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 81

3.

In an MDI application, you need to ensure that when the Product menu option is clicked, the Product form is displayed. Complete the code to display the Product form. Public Class Form1 Inherits System.Windows.Forms.Form

Private Sub Product_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Product.Click Dim NewMDIChild As New frmformdetails()

End Sub End Class Ans: You need to add the following lines after the NewMDIChild declaration: NewMDIChild.MdiParent = Me NewMDIChild.Show() 4. You have added a ContextMenu control to a Windows form. The ContextMenu control has the default name ContextMenu1. You have added three MenuItems named Product, Customer, and Sales to the ContextMenu1. How would you ensure that the MenuItems added to the ContextMenu1 would be display when a user right-clicks the Windows form?

Ans: You need to change the ContextMenu property of the Windows form from none to ContextMenu1. 5. Fill in the blank: You can add buttons to a ToolBar control by accessing the _____________________ editor. Ans: ToolBarButton Collection 6. You have added a ToolBar control and an ImageList control to the form, Form1. You have added four buttons to the ToolBar1 and four .bmps to the ImageList1.You need to specify the images for each of the toolbar buttons based on the following table:
Toolbar Button Name ImageName Position of the image in the ImageList collection 0 1 2 3

TbProduct TbCustomer TbSales TbExit

ProductImage CustomerImage SalesImage ExitImage

80 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged Me.ActiveForm.Controls(0).Text = "Text of the TextBox1 control has been changed" End Sub 22. Execute the application using the F5 key. 23. Click the Childform menu option to display the Childform form and verify if the text of the status bar panel changes as you type characters in the TextBox1 control.

FAQs
1. What is the difference between MDI forms in Visual Basic .NET and previous versions?

Ans: Two differences between MDI forms in Visual Basic .NET and previous versions are: 1. 2. In the previous versions of Visual Basic, MDI forms can contain controls that have the align property. In Visual Basic .NET an MDI form can contain any control. In the previous version of Visual Basic .NET, you can have only one MDI parent form. In Visual Basic .NET, you can have multiple MDI parent forms. However, no form can simultaneously be a MDI parent form and a MDI child form.

2.

How will you add a menu item dynamically?

Ans: You can add a menu item dynamically by performing the following steps: 1. 2. Drag a MenuItem control to a Form. By default, it is named as MenuItem1. Add the following code to add a menuitem at run time: Dim NewMenuItem As MenuItem() NewMenuItem.Text=New Menu Item MenuItem1.MenuItems.Add(NewMenuItem) 3. How will you add a submenu in an MDI form to list the MDI child forms currently loaded?

Ans: You can do this using the MDIList property of the MenuItem object.

Solutions: Just a Minute


1. How can you specify a Windows Form to be an MDI Parent form?

Ans: You need to set the IsMDIContainer property of the form to True to specify a Windows Form as an MDI Parent form. 2. Fill in the blank: ______________ objects are added to the ____________ collection to include menu options to a Windows form. Ans: MenuItem, MainMenu.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 79

Steps to add Messages from a Child form to an MDI Parent Form:


1. 2. 3. 4. 5. 6. 7. 8. 9. Start Microsoft Visual Studio .NET using the Start menu. Select the Project option from the New submenu under the File menu. Ensure that in the New Project dialog box, Project Types is Visual Basic Projects and Template is Windows Application. Type Status_bar in the Name text box and click the OK button. Double-click the StatusBar control in the Toolbox to add the control to Form1. Right-click StatusBar1 and selecting Properties option from the short-cut menu. Specify the Text property of the StatusBar1 as Form1 is Displayed. Right-click the Form1 and select Properties option from the short-cut menu. Set IsMdiContainer property to True. Double-click the MainMenu control in the Toolbox to add the control to Form1.

10. Add a menu item named Childform to the MDI Parent form, Form1. 11. Select Add Windows Form from the Project menu. 12. Specify the name of the form as childform and click the Open button. 13. Add a TextBox control to the childform. 14. Right-click TextBox1 and select the Properties option from the short-cut menu. 15. Clear the content of the Text property of TextBox1 control. 16. Select Form1 in the Solution Explorer and select the View Designer icon. 17. Double-click the menu item Childform to display the Code Editor window. 18. In the click() event of MenuItem1, write the following lines of code: Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Dim NewMDIChild As New childform() NewMDIChild.MdiParent = Me NewMDIChild.Show() End Sub 19. Select childform in the Solution Explorer and select the View Designer icon. 20. Double-click the TextBox1 control to display the Code Editor window. 21. In the TextChanged() event of TextBox1, write the following code:

78 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Replace the code for the Next button: Increases the position of the CurrencyManager by 1. OleDbDataAdapter1.Fill(DataSet11) bm.Position + = 1 Replace the code for the Previous button: Decreases the position of the CurrencyManager by 1. OleDbDataAdapter1.Fill(DataSet11) bm.Position - = 1 Replace the code for the First button: Sets the position of the CurrencyManager to 0. The CurrencyManager position starts from 0, the value 0 depicting the first record. OleDbDataAdapter1.Fill(DataSet11) bm.Position = 0 Replace the code for the Last button: Sets the position of the CurrencyManager to 1 less than the CurrencyManager count i.e. the total number of records in the list. OleDbDataAdapter1.Fill(DataSet11) bm.Position = bm.Count-1

Lesson Nine
Experiences
Tell students very briefly about menus and their types. Then, explain MDI applications. You can use Microsoft Word and Notepad as examples to explain MDI applications. You can then explain the technicalities of an MDI application in details. While teaching the ToolBar and ImageList controls, tell students that a button or a list box is a control. They have used these controls earlier and, therefore, will be able to relate easily. You need not explain controls in detail, as students would learn about controls in subsequent lessons.

Additional Inputs
You can also display user-defined messages in the panel of a status bar that is added to the MDI Parent form from a MDI Child form. The following example illustrates the steps that you need to implement to display user-defined messages in the panel of a status bar that is added to a MDI Parent form. To execute the following code, you need to have two forms, named Form1 and childform.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 77

dr(3) = TextBox4.Text dr(4) = TextBox5.Text dr(5) = TextBox6.Text t1.Rows.Add(dr) ElseIf flag = 3 Then t1 = DataSet11.Tables("CustomerTracking") dr = t1.Rows.Find(custid) dr.BeginEdit() dr(0) = custid dr(1) = TextBox2.Text dr(2) = TextBox3.Text dr(3) = TextBox4.Text dr(4) = TextBox5.Text dr(5) = TextBox6.Text dr.EndEdit() TextBox1.Enabled = True TextBox2.Enabled = True TextBox6.Enabled = True ElseIf flag = 2 Then dr.Delete() End If flag = 0 OleDbDataAdapter1.Update(DataSet11, "CustomerTracking") OleDbDataAdapter1.Fill(DataSet11) bm.Position=0 8. Write the following code for the Load event of the form: bm = Me.BindingContext(DataSet11, CustomerTracking) bm.Position = 0

76 Programming in Visual Basic .NET-Coordinator Guide

NIIT

5.

Replace the code for the Click event of the Delete button with the following code: custid = TextBox1.Text t1 = DataSet11.Tables("CustomerTracking") dr = t1.Rows.Find(custid) flag = 2

6.

Replace the code for the Click event of the Modify button with the following code: TextBox1.Enabled = False TextBox2.Enabled = False custid = TextBox1.Text flag = 3

7.

Replace the code for the Click event of the Save button with the following code: If flag = 1 Then If TextBox2.Text = "" Then MsgBox("The customer's first name cannot be left blank. Please enter the Employee Name", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox2.Focus() Exit Sub ElseIf TextBox4.Text = "" Then MsgBox("The customer's address cannot be left blank.", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox4.Focus() Exit Sub End If t1 = DataSet11.Tables("CustomerTracking") dr = t1.NewRow() dr(0) = TextBox1.Text dr(1) = TextBox2.Text dr(2) = TextBox3.Text

NIIT

Programming in Visual Basic .NET-Coordinator Guide 75

3.

Write the following code for the Load event of the form: bm = Me.BindingContext(DataSet11, "CustomerTracking") OleDbDataAdapter1.Fill(DataSet11)

4.

Replace the code for the Click event of the Add button with the following code: TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox4.Text = "" TextBox5.Text = "" TextBox6.Text = "" flag = 1 Dim ctr, len As Integer Dim custidval As String t1 = DataSet11.Tables("CustomerTracking") len = (t1.Rows.Count - 1) dr = t1.Rows(len) custid = dr("CustID") custidval = Mid(custid, 2, 3) ctr = CInt(custidval) If ctr >= 1 And ctr < 9 Then ctr = ctr + 1 TextBox1.Text = "C00" & ctr ElseIf ctr >= 9 And ctr < 99 Then ctr = ctr + 1 TextBox1.Text = "C0" & ctr ElseIf ctr >= 99 Then ctr = ctr + 1 TextBox1.Text = "C" & ctr End If TextBox1.Enabled = False

74 Programming in Visual Basic .NET-Coordinator Guide

NIIT

7.

The information under the Fields tab is displayed. All the fields of the QueryHandling table are displayed in the Available Fields list. To insert a field in the Crystal Report, select the field and click Add. In this case, click Add All to insert all the fields in the Crystal Report and click Next. The information under the Group tab is displayed. You can select the field on which you want to group the data in the Crystal Report and click Add. In this case, select QueryHandling.Sub_Date from the Available Fields list and click Add. The QueryHandling.Sub_Date field is included in the Group By list. In the Break list box, you can specify the break for grouping the data. For example, you can group data on a monthly basis, weekly basis, or daily basis. Select the for each week. option from the Break list box to group and display data on a weekly basis and click Next.

8.

9.

10. On the Total tab, do not change the default option in the Summary Type list box and click Next. 11. On the TopN tab, click Next. 12. On the Chart tab, click Next. 13. On the Select tab, click Next. 14. Under the Style tab, enter Employee Performance in the Title text box and click Finish. 15. Open the Form Designer and drag a CrystalReportViewer control from the Windows Forms tab of the Toolbox. 16. Resize the CrystalReportViewer control so as to display all the data at run time. 17. Write the following code in the Click event of the Show Revenue Report button: CrystalReportViewer1.ReportSource= D:\Visual Project\WindowsApp\CrystalReport1.rpt The actual path will vary according to the path where the project is saved. 18. Write the following code in the Click event of the Show Employee Performance Report button: CrystalReportViewer1.ReportSource= D:\Visual Project\WindowsApp\CrystalReport2.rpt 19. Run the application. Note: Ask the students to save the application in the Home Directory as the same application would be used for 11.P.1

UGP 2
The correct code is as follows: 1. 2. Open the application CustomerDetails. Add the following form-level declaration: Dim bm as BindingManagerBase

NIIT

Programming in Visual Basic .NET-Coordinator Guide 73

10. Under the Data tab, the Available data sources pane displays the connection and the corresponding database, which you created by following the above steps. Click the plus sign next to the database name CallCenter11. The existing tables in the database CallCenter11 are displayed. 11. Select the CustOrder table and click Insert Table to insert the table in the Crystal Report. Then, click Next. 12. The information under the Fields tab is displayed. All the fields of the CustOrder table are displayed in the Available Fields list. To insert a field in the Crystal Report, select the field and click Add. In this case, click Add All to insert all the fields in the Crystal Report and click Next. 13. The information under the Group tab is displayed. You can select the field on which you want to group the data in the Crystal Report and click Add. In this case, select CustOrder.Date from the Available Fields list and click Add. The CustOrder.Date field is included in the Group By list. 14. When the CustOrder.Date field is inserted in the Group By list, a Sort Order and a Break list box is displayed below the Group By list. You can use the Sort Order list box to select the method to sort the data. For example, you can specify the data to be displayed in an ascending order, descending order, original order (in the same order as it exists in the database), or in a specified order, where you can select the fields in the order in which they would be displayed. By default, in ascending order. option is selected in the Sort Order list box. Do not change the default option. 15. In the Break list box, you can specify the break for grouping the data. For example, you can group data on a monthly basis, weekly basis, or daily basis. Select the for each week. option from the Break list box to group and display data on a monthly basis and click Next. 16. Under the Total tab, do not change the default option in the Summary Type list box and click Next. 17. Under the TopN tab, click Next. 18. Under the Chart tab, click Next. 19. Under the Select tab, click Next. 20. Under the Style tab, enter Week-Wise Revenue in the Title text box and click Finish. Create another report by performing the following steps: 1. 2. 3. 4. 5. Right-click the Project name in the Solution Explorer window and point to Add from the shortcut menu. Then, click Add New Item from the Add submenu. The Add New Item - <Application name> dialog box is displayed. Select Crystal Report from the Templates pane in the right side of the Add New Item <application name> dialog box. By default, the Crystal Report is named as CrystalReport2.rpt. Click Open. Crystal Report Gallery is displayed. Then, select the Using the Report Expert option from Crystal Report Gallery and click OK. On the Data tab, the Available data sources pane displays the connection and the corresponding database, which you created by following the above steps. Click the plus sign next to the database name CallCenter11. The existing tables in the database CallCenter11 are displayed. Select the QueryHandling table and click Insert Table to insert the table in the Crystal Report. Then, click Next.

6.

72 Programming in Visual Basic .NET-Coordinator Guide

NIIT

17. Under the Customize Style tab, click Next. 18. Under the Chart tab, click Next. 19. Under the Select tab, select QueryHandling.Sub_Date from the Available Fields list and click the Add-> button to add the field in the Select Fields list. 20. In the list box below the Select Fields list, is any value. option is selected by default. Select is greater than from the list box. 21. After is greater than is selected in the list box, a combo box is displayed, where you can specify the criterion. Select 7/9/2001 12:00:00AM from the combo box and click Finish. 22. Save the Crystal Report by using the File Save CrystalReport1.rpt option. 23. Open the Form Designer window and drag a CrystalReportViewer control from the Windows Forms tab of the Toolbox. 24. Resize the CrystalReportViewer control so as to display all the data at run time. 25. Open the Properties window for the CrystalReportViewer control and click the ReportSource property. 26. Select Browse from the drop-down list and select CrystalReport1 in the Open an Existing Crystal Report dialog box. Then, click Open. 27. Run the application.

Solution: Unguided Practice UGP 1


1. 2. Create a new Windows Application project. Form1 is added to the application by default. Drag two Button controls from the Windows Forms tab of the Toolbox into the form and set the their Text property to Show Revenue Report and Show Employee Performance Report, respectively. Right-click on the Project name in the Solution Explorer window and point to Add from the shortcut menu. Then, click Add New Item from the Add submenu. The Add New Item - <Application name> dialog box is displayed. Select Crystal Report from the Templates pane in the right side of the Add New Item <Application name> dialog box. By default, the Crystal Report is named as CrystalReport1.rpt. Click Open. Crystal Report Gallery is displayed. Then, select the Using the Report Expert option from Crystal Report Gallery and click OK. Expand the OLE DB (ADO) folder in the Available data sources list and then select Microsoft OLE DB Provider for SQL Server from the Provider list. Click Next. Provide the information, such as the server name to connect, the user ID and password for connecting with the server, and the database name as CallCenter11. Click Next. Click Finish in the Advanced Information screen.

3. 4. 5. 6. 7. 8. 9.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 71

8.UGP.1
Before running 8.UGP.1, perform the following steps: 1. 2. 3. Copy the project folders in the local machine. Open the Code Editor window for the form. Change the code for the Click event of both the buttons to: CrystalReportViewer1.ReportSource =<path of the crystal report file eg. C:\My Documents\8.D.1\CrystalReport1.rpt>

Solution: Guided Practice 8.P.1


1. 2. 3. 4. 5. 6. 7. 8. 9. Create a new Windows Application project. Form1 is added to the application by default. Click File from the menu bar. Then, select Add New Item from the File menu. Select Crystal Report from the Templates pane of the Add New Item <application name> dialog box and click Open. In the Crystal Report Gallery, the Using the Report Expert radio button is selected by default. Select the Cross-Tab expert from the Choose an Expert list and click OK. Under the Data tab, expand the OLE DB (ADO) folder. In the ADO DB (ADO) dialog box, select Microsoft OLE DB Provider for SQL Server from the Provider list. Click Next. Provide the information, such as the server name to connect, the user ID and password for connecting with the server and enter CallCenter11 in the Database combo box. Click Next. Click Finish in the Advanced Information screen. Expand CallCenter11 database in the Available data sources list. Select the QueryHandling table from the Available data sources list and click the Insert Table button. Then, click Next.

10. The information under the Cross-Tab tab is displayed. Select EmpID in the Available Fields list and click Add Column button. 11. Select QID in the Available Fields list and click Add Row button. 12. Select Sub_Date in the Available Fields list and click Add Row button. 13. Select Feedback in the Available Fields list and click Add Summarized Field button. 14. Click the Change Summary button. In the Change Summary dialog box, select average from the list box and click OK. 15. Click Next. 16. Under the Style tab, do not change the default style and click Next.

70 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Explain the toolbar icons of the Windows Forms Viewer by creating a simple Windows Form and adding a CrystalReportViewer control, as shown below:

A Sample Windows Form

Additional Inputs
Demos and Practices
The solutions for demos, guided practices, and unguided practices for this lesson are stored in the Solutions\Lesson8 folder. To execute the demos, guided practices, and unguideded practices, perform the following steps: 1. 2. 3. Copy the project folders in the local machine. Open the Properties window for the HelpProvider control. Set the HelpNameSpace property to the path where the Crystal Report file is present (eg. C:\My Documents\8.D.1\CrystalReport1.rpt). 8.D.1 will be used for 12.UGP.1.

Note:

8.D.2
8.D.2 requires ADO.NET connectivity. Therefore, follow the steps given for Lesson Five before running the application.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 69

For the First button: Sets the position of the CurrencyManager to 0. The CurrencyManager position starts from 0, the value 0 depicting the first record. OleDbDataAdapter1.Fill(DataSet11) bm.Position = 0 For the Last button: Sets the position of the CurrencyManager to 1 less than the CurrencyManager count i.e. the total number of records in the list. OleDbDataAdapter1.Fill(DataSet11) bm.Position = bm.Count-1 Note: Ask the students to save the application in the Home Directory as it will be used for 12.P.1.

Lesson Eight
Experiences
While discussing the data access model of Crystal Reports, explain to students that the Pull method is widely used to access data from a database, because this method ensures fast data access. Windows Forms Viewer is an important concept as it allows viewing a Crystal Report in a windows application. Discuss Windows Forms Viewer and the CrystalReportViewer control in detail, as students might get confused initially.

68 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Exit Sub ElseIf TextBox6.Text = "" Then MsgBox("The customer's email address cannot be left blank.", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox6.Focus() Exit Sub End If t1 = DataSet11.Tables("CustomerTracking") dr = t1.NewRow() dr(0) = TextBox1.Text dr(1) = TextBox2.Text dr(2) = TextBox3.Text dr(3) = TextBox4.Text dr(4) = TextBox5.Text dr(5) = TextBox6.Text t1.Rows.Add(dr) End If Code for the Load event of the Form: bm = Me.BindingContext(DataSet11, CustomerTracking) bm.Position = 0 For the Next button: Increases the position of the CurrencyManager by 1. OleDbDataAdapter1.Fill(DataSet11) bm.Position + = 1 For the Previous button: Decreases the position of the CurrencyManager by 1. OleDbDataAdapter1.Fill(DataSet11) bm.Position - = 1

NIIT

Programming in Visual Basic .NET-Coordinator Guide 67

4.

Use the forms Customer, Order, Query, and Employee created in Lesson3 and Lesson4 for this demo. Write the following code for the Click event of the Delete button: custid = TextBox1.Text t1 = DataSet11.Tables("CustomerTracking") dr = t1.Rows.Find(custid) flag = 2

5.

Write the following code for the Click event of the Modify button: TextBox1.Enabled = False custid = TextBox1.Text flag = 3

6.

Write the following code for the Click event of the Save button: If flag = 1 Then If TextBox2.Text = "" Then MsgBox("The customer's first name cannot be left blank. Please enter the Employee Name", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox2.Focus() Exit Sub ElseIf TextBox3.Text = "" Then MsgBox("The customer's last name cannot be left blank.", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox3.Focus() Exit Sub ElseIf TextBox4.Text = "" Then MsgBox("The customer's address cannot be left blank.", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox4.Focus() Exit Sub ElseIf TextBox5.Text = "" Then MsgBox("The customer's phone number cannot be left blank.", MsgBoxStyle.OKOnly, "Incomplete Information") TextBox5.Focus()

66 Programming in Visual Basic .NET-Coordinator Guide

NIIT

3.

Write the following code for the Click event of the Add button: TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox4.Text = "" TextBox5.Text = "" TextBox6.Text = "" flag = 1 Dim ctr, len As Integer Dim custidval As String t1 = DataSet11.Tables("CustomerTracking") len = (t1.Rows.Count - 1) dr = t1.Rows(len) custid = dr("CustID") custidval = Mid(custid, 2, 3) ctr = CInt(custidval) If ctr >= 1 And ctr < 9 Then ctr = ctr + 1 TextBox1.Text = "C00" & ctr ElseIf ctr >= 9 And ctr < 99 Then ctr = ctr + 1 TextBox1.Text = "C0" & ctr ElseIf ctr >= 99 Then ctr = ctr + 1 TextBox1.Text = "C" & ctr End If TextBox1.Enabled = False This code displays blank controls in the Form so that the user can enter values for the new record. A flag is created to identify the action performed by the user before the Save button is clicked.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 65

To connect to the database, perform the following steps: 1. Create a data adapter named OleDbDataAdapter1 for the connection through Data Adapter Configuration Wizard. a. On the second screen of the wizard, connect to the database CallCenter11. b. c. In the third screen of the wizard, choose the Use SQL statements option as the method of retrieving data and click Next. In the fourth screen, click Query Builder button. In Query Builder, add the table CustomerTracking and then select the ( All Columns) check box to select all its columns.

The query generated in the third pane of the Query Builder would resemble the one shown below: SELECT CustomerTracking.* FROM Employees 2. 3. Generate a new dataset DataSet1 for OleDbDataAdapter1. Make the Text property blank for all the TextBox controls. When the Text property under the DataBindings category in the Properties window is clicked, a down arrow is displayed. Clicking on the down arrow displays a list of datasets and the corresponding tables. The tables contain the existing column names. The column names to be selected from the table CustomerTracking for the Text property of each of the TextBox controls are specified in the following table:

TextBox TextBox1 TextBox2 TextBox3 TextBox4 TextBox5 TextBox6 CustID FName LName Address Phone email

Text Property

To maintain the data, perform the following steps: 1. Make the following form-level declarations: Dim flag as integer Dim custid as string Dim dr as DataRow Dim t1 As DataTable Dim bm as BindingManagerBase 2. Write the following code for the Load event of the Form: OleDbDataAdapter1.Fill(DataSet11) This statement will fill the dataset DataSet11 with the table values.

64 Programming in Visual Basic .NET-Coordinator Guide

NIIT

3.

Set the Text property for the Label controls as shown in the following table:
Label Label1 Label2 Label3 Label4 Label5 Label6 Customer ID First Name Last Name Address Phone email Text Property

4.

Drag eight Button controls to the Form. The Text property under the Appearance category in the Properties window needs to be set, as displayed in the following table:
Button Button1 Button2 Button3 Button4 Button5 Button6 Button7 Button8 First Previous Next Last Add Modify Delete Save Text Property Function To display the first record of the dataset To display the next record of the dataset To display the previous record of the dataset To display the last record of the dataset To display an empty record where a user can enter values To allow the user to modify a record To allow a user to delete a record To save the action performed by the user into the database. Whenever a user adds, modifies, or deletes a record, the database will be updated only when this button is clicked

A sample Windows Form designed by implementing the above given steps is shown in the following figure:

NIIT

Programming in Visual Basic .NET-Coordinator Guide 63

To access data that is not appropriate for storing data in a dataset, such as the data with a short life cycle. For example, retrieving data about daily transactions may not be needed to be stored in a dataset To access read-only data, which will not be updated


5. Ans:

Write a code to connect to a database through data commands? The code to connect to a database through data commands is as follows: Dim Str1 as String = provider=sqloledb;user id=sa;password=;database=CallCenter12;server=DEVSERVER Dim Str2 as New OleDb.OleDbConnection(str1) Str2.Open()

6. Ans:

What is the difference between the concurrency control through Saving All method and the Version Number method? In the Version Number method, when the record is read, a DateTimeStamp or a version number column is saved on the client. The data is updated only if the saved DateTimeStamp matches the DateTimeStamp on the record while in the Saving All method, when the retrieved data is changed in the dataset, the dataset stores both the original and the current versions of the data. While updating the database, the original version of the records is compared to the records in the database.

Solution: Guided Practice 7.P.1


The data to be displayed:

CustID Fname LName Address Phone email


1. Create a new Visual Basic Windows Application project by clicking the New Project button in the Microsoft Development Environment [design] - Start Page. Form1 is added to the project by default. From the Windows Forms tab of the Toolbox, drag eight Label controls and eight TextBox controls to display the values from the columns EmpID, EFirstName, ELastName, Address, Age, D_Join, Dept, and Salary.

2.

62 Programming in Visual Basic .NET-Coordinator Guide

NIIT

After this, the first user tries to change the value of Salary to 3750.
Column EmpID EmpName Salary Original Value E002 Collin 3200 Current Value E002 Miller 3750 Value in the Database E002 Collin 3500

At this point, the first user encounters an error since the record that the user had retrieved from the database does not match with the database record. Therefore, optimistic concurrency control does not allow a user to change a record if that record has been changed after the user retrieves it.

Additional Inputs
The solutions for demos and guided practices for this lesson are stored in the Solutions\VB.NET\Lesson7 folder.

FAQ
1. Ans: Can we combine data from two different datasets into one dataset? Yes. You can copy records from one dataset into another dataset by using the Merge() method of the target dataset( the dataset into which the records are to be copied) and passing it to the dataset from which the records are to be copied.

Solutions: Just A Minute


1. Ans: What are the events raised at the time of data updation? The events raised at the time of data updation are:

ColumnChanging RowChanging ColumnChanged RowChanged


2. Ans: 3. Ans: When does the RowState property have the value Detached? The RowState property has value Detached between the time that it is created till it is added to a collection, or if it has been removed from a collection. What is the relationship between the RowState property and the DataRowVersion enumeration? When changes have been made to a row and the data source has to be updated, the RowState property tells you about the state of the dataset as represented by any of the four constants of the DataRowVersion enumeration. In which cases, direct data update is preferred to updates through datasets? Direct data updates are generally used in the following cases:

4. Ans:


NIIT

To work with stored procedures that return a result set, which can be manipulated

Programming in Visual Basic .NET-Coordinator Guide 61

3.

While configuring the data adapter, in the third pane of the Query Builder, add the following line to the query:

Where ProdID = P011 Code for the Click event of the Display button: OleDbDataAdapter1.Fill(DataSet11) Other steps remain the same.

Lesson Seven
Experiences
Introduce the concept of data updating data in present scenario where applications should allow users to add, modify, and delete data from the database without explicitly giving database commands. While discussing cached and direct data updates, explain to the students that in both the cases the database is updated through database commands. The difference is that in cached data updates, the user need not give data update commands explicitly, whereas in case of direct data updates, the user needs to give commands to update the database. Explain the concept of optimistic concurrency control by giving the following example: A table Employees is present in a database. Suppose the first user reads a record with the following values EmpID E002
Column EmpID EmpName Salary

EmpName Collin

Salary 3200
Original Value E002 Collin 3200 Current Value E002 Collin 3200 Value in the Database E002 Collin 3200

Immediately after that, the second user reads the same record. Then, the second user changes Salary from 3200 to 3500 and tries to update the database.
Column EmpID EmpName Salary Original Value E002 Collin 3200 Current Value E002 Collin 3500 Value in the Database E002 Collin 3200

The user is able to update the database since the original value retrieved by the user matches the value in the database.

60 Programming in Visual Basic .NET-Coordinator Guide

NIIT

1. 2. 3. 4. 5. 6. 7. 8. 9.

Open the application EmployeeData. Right-click OleDbDataAdapter2 from the component tray and select Configure Data Adapter from the shortcut menu. On the fourth screen of the wizard, click the Query Builder button. Add the QueryHandling table and then select its the columns (including EmpID) for generating the SQL statement. Then, click OK. Click Next and then click Finish to complete the wizard. Right-click any of the data adapters in the component tray and select Generate Dataset from the shortcut menu. In the Generate Dataset dialog box, select the New radio button containing the name DataSet1. Ensure that both the tables are selected under the Choose which table(s) to add to the dataset list and click OK. Open the file DataSet1.xsd from the Solution Explorer window.

10. From the XML Schema tab of the Toolbox, drag a Relation object to the Employee table. 11. Set the following options in the Edit Relation dialog box: Name: EmployeesQueryhandling Parent Element:Employees Child Element: QueryHandling Key Fields: EmpID Foreign Key Fields: EmpID 11. Bind the DataGrid control by setting the DataSource property to DataSet11 and the DataMember property to Employees EmployeesQueryHandling. 12. Bind the ListBox control by setting the DataSource property to DataSet11 and DisplayMember property to Employees.EmpID. 13. Write the following code for the Load event for the Form: OleDbDataAdapter1.Fill(Dataset11, Employees) OleDbDataAdapter2.Fill(Dataset11, QueryHandling)

UGP 3
Open the application ProductDetails. 1. 2. Remove the dataset on the component tray. Also remove the Dataset1.xsd. Right-click OleDbDataAdapter1 and select Configure Data Adapter from the shortcut menu.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 59

15. Write the following code for the Load event of Form1. OleDbDataAdapter1.Fill(Dataset11) Code for the Load event of Form1: bm = Me.BindingContext(DataSet11, CustOrder) bm.Position = 0

Code for the Next button: Increases the position of the CurrencyManager by 1. bm.Position + = 1 Code for the Previous button: Decreases the position of the CurrencyManager by 1. bm.Position - = 1 Code for the First button: Sets the position of the CurrencyManager to 0. The CurrencyManager position starts from 0, the value 0 depicting the first record. bm.Position = 0 Code for the Last button: Sets the position of the CurrencyManager to 1 less than the CurrencyManager count i.e. the total number of records in the list. bm.Position = bm.Count - 1

UGP 2
Data to be displayed:

QID Sub_Date Cust_Name Emp_ID Date Status Feedback

58 Programming in Visual Basic .NET-Coordinator Guide

NIIT

A sample Windows Form designed by following the above steps is shown in the figure below.

To bind the data to the controls, follow the given steps: 13. For a TextBox control, when the Text property under the DataBindings category is clicked, a down arrow is displayed. Clicking on the down arrow displays the list of datasets and corresponding tables. The tables contain the existing column names. The column names to be selected from the table CustOrder for the Text property of each of the TextBox controls are given below:
TextBox TextBox1 TextBox2 TextBox3 TextBox4 TextBox5 TextBox6 TextBox7 Inv Date CustID ProdID Cost Advance Profit Text Property

14. Make the following general level declaration: Dim bm as BindingManagerBase

NIIT

Programming in Visual Basic .NET-Coordinator Guide 57

5. 6. 7. 8.

In the first column of the first blank line of the table grid, select the element option from the drop-down list. In the next column in the same line, enter Profit as name for the column. In the last column of the line, select integer as the data type for the column from the drop-down list. Select the new column in the table grid. Click View from the menu bar. Then, select Properties Window from the View menu. Enter the following expression in the Expression property for the column: Cost-2500

9.

Save and close DataSet1.xsd.

10. Select OleDbDataAdapter1 from the component tray. 11. Select Data from the menu bar and then select the Preview Data option from the displayed list. 12. The Data Adapter Preview window is displayed. Select OleDbDataAdapter1 from the Data adapters list box. 13. By default, the target dataset is DataSet1. Click the Fill Dataset button to fill the dataset created with the records from the CustOrder table. 14. The records from the CustOrder table are displayed in a tabular format in the Results pane of the Data Adapter Preview window. Click Close to close the Data Adapter Preview window. Design a Windows Form to display data by performing the following steps: 1. 2. 3. Select View from the menu bar and then select Toolbox from the View menu. The Toolbox is displayed on the left of the window. From the Windows Forms tab of the Toolbox, drag seven Label controls and seven TextBox controls to display the values from the Inv, Date, CustID, ProdID, Cost, and Profit columns. Set the Text property for the Label controls, as shown in the following table:
Label Label1 Label2 Label 3 Label 4 Label 5 Label 6 Label 7 Invoice Date Customer ID Product ID Cost Advance Profit Text property

4.

Drag four Button controls to the Form. The function of each Button control and the Text property to be set for each button is displayed in the following table.
Button Button1 Button2 Button3 Button4 First Previous Next Last Text property Function To display the first record of the dataset. To display the next record of the dataset To display the previous record of the dataset To display the last record of the dataset

56 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Solution: Unguided Practice UGP 1


Data to be displayed:

Inv Date CustID ProdID Cost Profit


1. Create a new Visual Basic Windows Application project by clicking the New Project button in Microsoft Development Environment [design] - Start Page. Form1 is added to the project by default. Select View from the menu bar and then select Toolbox from the View menu. The Toolbox is displayed on the left of the screen. From the Data tab of the Toolbox, drag OleDbDataAdapter on to Form1. The Data Adapter Configuration Wizard welcome screen is displayed. Click the Next button. On the next screen, make a new connection to the CallCenter11 database. On the next screen, ensure that the Use SQL statements radio button is selected. Click Next. On the next screen, click the Query Builder button. When the Query Builder opens, the Add Table dialog box is displayed. Select the CustOrder table and click the Add button to add the table to the Query Builder. The table is added to the Query Builder. Click Close to close the Add Table dialog box. Select the Inv, Date, CustID, ProdID, Advance, and Cost fields from the CustOrder table. Click OK after selecting the fields. The designed query is displayed on the screen. Click Next to build the query. The last screen of the wizard displays the message that the data adapter has been configured successfully. It also displays the statements generated by the data adapter to select, insert, update, and delete the table records. Click Finish to close the Data Adapter Configuration Wizard.

2. 3. 4. 5. 6. 7.

8. 9. 10. 11. 12.

Create a dataset for storing records by following the given steps: 1. 2. 3. Click Data from the menu bar. Select Generate Dataset from the Data menu. The Generate Dataset dialog box is displayed. The New radio button would be selected by default since there are no existing datasets. The CustOrder table checkbox would be selected by default. Do not change the default option and click OK. The dataset is added to the component tray. Open Dataset1.xsd by double-clicking it in the Solution Explorer window.

4.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 55

Even when no DataView object is created for a data table, the data table has a default DataView object that can be used to filter and sort data. The default DataView object can be accessed by using the DefaultView property of the data table, shown below: Dim t1 As DataTable t1 = DataSet1.Tables("Employees") t1.DefaultView.RowFilter = "Age < 45"

Demos and Practices


The solutions for demos, guided practices, and unguided practices for this lesson are stored in the Solutions\VB.NET\Lesson 6 folder. The projects to be provided to the students for 6.UGP.2 and 6.UGP.3 are present in the Data Files\VB.NET\Lesson6 folder.

FAQ
1. Can we use both simple and complex binding in a single application?

Ans: Yes. Since you can use different controls in an application, both simple and complex binding can be implemented in a single application.

Solutions: Just A Minute


1. Ans: What is the difference between simple data binding and complex data binding? What are the controls used in each type of binding? Simple data binding is the process of binding a control, such as a TextBox or a Label control, to a value in a dataset. The dataset value can be bound to the control by using the properties of the control. A Textbox control is used for simple binding. While simple data binding involves binding a control to a dataset value, complex data binding is the process of binding a component to display multiple values for a column from the dataset rows. The DataGrid, Listbox, and ComboBox controls are used for complex binding. 2. The records of customers having monthly income of $4200 need to be displayed in the ascending order of their names from the table Employees. Write the code to retrieve filtered records and store the retrieved records. The code is as follows: Dim t1 As DataTable t1 = DataSet11.Tables("Employees") Dim str1 As String Dim str2 As String str1 = "Income > 4200" str2 = "Name ASC" Dim result() As DataRow result = t1.Select(str1, str2)

Ans:

54 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Lesson Six
Experiences
Start the session by recalling the concepts covered in lesson 5 covered how to preview data in the database in a tabular format. Then, explain the need and benefits of displaying data in a customized format. Explain the difference between simple and complex data binding through the example of a Student Registration form for a university. You can use the following controls in your example:
Control TextBox ListBox ComboBox Purpose To display the student name, age, and address To display the list of courses offered by the university To display class timings where the student can select from existing timings or enter the timing To display records in a tabular format where the records can be added, modified, or deleted

DataGrid

While explaining how to filter a dataset, explain that when the filter criterion is known at design time, parameterized queries should be used. Explain the function of the CurrencyManager and BindingContext classes clearly since students might find it confusing initially.

Additional Inputs
Filtering a Dataset
A dataset can be filtered by using the versions of the records in the dataset. When a dataset is populated for the first time, it contains the original version of records. When the data is changed, the dataset contains the original as well as the modified version of records. The record version can be used as the third parameter of the Select() method. For example, Dim Str1, Str2 as string Str1 = Age > 30 Str2 = Name DESC t1 = DataSet1.Tables("Employees").Select(Str1,Str2, DataViewRowState.OriginalRows) The above code retrieves employee details for employees whose age exceeds 30 years in the ascending order of their names. The rows that will be retrieved will be the original rows. Some other versions of a dataset are CurrentRows, Added, and Unchanged.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 53

11. On the next screen, ensure that the Use SQL statements radio button is selected. Click Next. 12. On the next screen, click the Query Builder button. 13. When the Query Builder opens, the Add Table dialog box is displayed. Select the CustOrder table and click the Add button to add the table to the Query Builder. The table is added to the Query Builder. 14. Click Close to close the Add Table dialog box. 15. Select all the fields of the CustOrder table. 16. Click OK after selecting the fields. The designed query appears in the screen. 17. Click Next to build the query. 18. The last screen of the wizard displays the message that the data adapter has been configured successfully. It also displays the statements generated by the data adapter to select, insert, update, and delete table records. Click Finish to close the Data Adapter Configuration Wizard. Create a dataset for storing the records by performing the following steps: 1. 2. 3. Click Data from the menu bar. Select Generate Dataset from the Data menu. The Generate Dataset dialog box is displayed. The New radio button would be selected by default since there are no existing datasets. The CustOrder table checkbox is selected by default. Accept default options and click OK. The dataset is added to the component tray. Open Dataset1.xsd by double-clicking it in the Solution Explorer window. Click the first column in the first blank line of the table grid and select the element option from the drop-down list. In the next column in the same line, enter Percentage as name for the column. In the last column of the line, select integer as the data type for the column from the drop-down list. Select the new column in the table grid. Click View from the menu bar. Then, select Properties Window from the View menu. Enter the following expression in the Expression property for the column: Advance/Cost * 100 9. Save and close DataSet1.xsd. Then, select OleDbDataAdapter1 from the component tray.

4. 5. 6. 7. 8.

10. Select Data from the menu bar. Then select the Preview Data option from the Data menu. 11. The Data Adapter Preview window is displayed. Select OleDbDataAdapter1 from the Data adapters list box. 12. By default, the target dataset is DataSet1. Click the Fill Dataset button to fill the dataset created with the records from the CustOrder table. 13. The records from the CustOrder table are displayed in a tabular format in the Results pane of the Data Adapter Preview window.

52 Programming in Visual Basic .NET-Coordinator Guide

NIIT

3.

Change the datasource, user ID, and password according to the requirements. For example, set the name of the data source to the name of the database server from where data has to be accessed and change the ID and password for the SQL server according to the ID and the password required to log on to the server. Save the project and run the application.

4.

NOTE: Ensure that the steps given above are performed before executing all the demos guided practices, and unguided practices involving ADO.NET connectivity.

Solution: Guided Practice 5.P.1


Data to be displayed:

Inv Date FName ProductID Cost Advance


1. 2. 3. 4. Create a new Visual Basic Windows Application project by clicking the New Project button in Microsoft Development Environment [design] - Start Page. Form1 is added to the project. From the Tools menu, select the Connect to Database option. The Data Link Properties dialog box is displayed. In the Select or enter a server name combo box under the Connection tab, enter the server name or select the server name to which the application will connect. Next, provide the information about how to log on to the server. You can either choose to log on to the server by using Windows NT integrated security or specify the user name and password for connecting to the server. Next, enter the name the database from which you want to access the data or select the database from the Select the database on the server combo box. In this case, select the database CallCenter11 from the list box. You can test whether the connection has been created successfully or not by clicking the Test Connection button. If the connection has been created successfully, the message Test connection succeeded is displayed. Click OK to close the message box. Click OK to apply all the specified settings and close the Data Link Properties dialog box. Select View from the menu bar and then select Toolbox from the View menu. From the Data tab of the Toolbox, drag the OleDbDataAdapter object into Form1. The Data Adapter Configuration Wizard welcome screen is displayed. Click the Next button.

5.

6.

7. 8. 9.

10. On the next screen, select the data connection for the data adapter from the list box.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 51

Emphasize that since most of the data retrieval applications also need to manipulate the data, such as adding, deleting, and modifying data, DataReaders do not find much use. The following code can be used as an example for retrieving data through DataReader: Dim Command1 As OleDb.OleDbCommand Dim DataReader1 As OleDb.OleDbDataReader Dim Str1 As String = "provider=sqloledb;user id=sa;password=;database=CallCenter11;server= DEVSERVER1" Dim Str2 As New OleDb.OleDbConnection(Str1) Str2.Open() Command1 = New OleDb.OleDbCommand("Select * from Employees", Str2) DataReader1 = Command1.ExecuteReader() DataReader1.Read() TextBox1.Text = DataReader1.GetString(0) TextBox2.Text = DataReader1.GetString(1) TextBox3.Text = DataReader1.GetString(1) DataReader1.Close() Str2.Close() The NextResult() method of the DataReader object sets the DataReader to read the next result.

Creating Untyped Dataset


An untyped dataset can be created by dragging DataSet from the Data tab of the Toolbox onto the form. A blank dataset is added to the component tray. Tables, columns, and rows can be added to the dataset by using the Properties window or syntactically as shown in the following example: DataSet1.Tables.Add("Employees") DataSet1.Tables("Employees").Columns(0).ColumnName = "EmpID"

Demos and Practices


The solutions for demos and practices for this lesson are stored in the Solutions\Lesson5\ folder. You need to perform the following steps to execute all the demos and practices involving ADO.NET: 1. 2. Open the Form Designer window. Open the Properties window for the OleDbConnection object present in the component tray. The ConnectionString property of the OleDbConnection object has the following entries: Provider=SQLOLEDB.1;User ID=sa;pwd=;Initial Catalog=CallCenter11;Data Source=localhost

50 Programming in Visual Basic .NET-Coordinator Guide

NIIT

While disconnected data processing in ADO is done by calling the OLE DB providers, in
ADO.NET this is done through data adapter, which calls the OLE DB providers. Thus, all the database operations, such as data validity and performance optimization are done by a data adapter.

In ADO, a recordset can be shared between applications by using COM marshalling. On the other
hand, ADO.NET is entirely based on XML and datasets can be shared between applications just by transmitting its XML schema. Transmitting XML files provides advantages over COM, such as richer set of data types, no need for data type conversion (COM marshalling requires the recordset data types to COM data types).

Creating a Dataset and a DataRelation Object


A dataset can be created programmatically as follows: Dim ds1 As DataSet = New DataSet("Employees") The following example illustrates the creation of a DataRelation object for linking the tables in a dataset: Dim dc1,dc2 as DataColumn dc1 = DataSet11.Tables("CustomerTracking").Columns("CustID") dc2 = DataSet11.Tables("CustOrder").Columns("CustID") Dim dr1 As DataRelation dr1 = New DataRelation("CustOrder", dc1, dc2) Dataset11.Relations.Add(dr1)

DataReader
The following diagram illustrates the working of a DataReader object:

APPLICATION

DATAREADER

CONNECTION

EXECUTEREADER COMMAND

The ExecuteReader() method of a Command object is used to send the command text to the Connection object. The Connection object creates a DataReader object and stores the result of the command execution within it. Accessing data through DataReader is fast since it directly retrieves data from the data source.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 49

2. Ans:

What are the various components of a dataset? The components of a dataset object model are Relations collection, Tables collection, DataRelation, DataTable, Rows collection, Columns collection, DataRow, and DataColumn. What is the function of a data adapter? A data adapter is integral to the working of ADO.NET since data is transferred to and from a database through a data adapter. A data adapter creates a dataset and updates the database. When you make any changes to the dataset, the modifications to the database are actually performed by the data adapter. List the features of ADO.NET. The main features of ADO.NET are:

3. Ans:

4. Ans:


5. Ans:

Disconnected data architecture Data cached in datasets Data transfer in XML format

What are the different methods of creating a data adapter? The methods for creating a data adapter are:


6. Ans:

Manually Through Server Explorer Through Data Adapter Configuration wizard

What is the difference between a typed and an untyped dataset? A typed dataset is derived from the base DataSet class and has an associated XML schema, which is created at the time of the creation of the dataset, whereas an untyped dataset does not have any associated XML schema. In an untyped dataset, tables and columns are represented as collections. Since an XML schema is not created for an untyped dataset, the structure of an untyped dataset is not known at the time of compilation.

Additional Inputs
Difference between ADO and ADO.NET
There are some major differences between ADO and ADO.NET. Theses are listed below:

There are no recordset objects in ADO.NET. Instead, the data is stored in datasets. In ADO, recordsets use the JOIN query to stores multiple tables, whereas datasets can contain data
retrieved from multiple tables by creating multiple DataTable objects. In addition, datasets can also stores the information about relationships between tables.

Navigation in ADO is done through the MoveNext() method. In ADO.NET, since tables and
their rows are represented as collections, a user can navigate through a table by using a primary key index.

48 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Lesson Five
Experiences
Introduce the concept of ADO.NET in the context of present business scenario where organizations store data at a centrally located database and different departments access the data from the same database. Explain that need for ADO.NET in relation to the users who want to access the database but do not know database commands for accessing data. The ADO.NET object model is an important concept. The students should be able to distinguish the different components of the ADO.NET object model and understand the working of each one of them clearly. While explaining the components of the ADO.NET object model, do not cover data readers in detail, as students would not use them in any of the chapters. However, do bring out the difference between a dataset and a data reader clearly. Explain the benefit of using disconnected data architecture, as it is the most important feature of ADO.NET.

FAQs
1. Do I need to any additional component or make any modifications in the registry to work with ADO.NET?

Ans: No, configuration of ADO.NET is handled while installing VS.NET. You do not need to modify any registry settings for working with ADO.NET 2. Which is the most efficient method of accessing data from a data source?

Ans: Accessing data through a dataset is the most efficient method since it needs connection to the data source for the least amount of time and the retrieved data can be easily manipulated. 3. Is the code for the SQL data provider different from the OLEDB data provider?

Ans: If you have written a code for the SQL data provider, you just have to change the connection type from SQLConnection to OLEDBConnection and the connection string to use the same code for an OLEDB data provider. 4. Can we set a relationship between tables even if the relationship does not exist in the database?

Ans: Yes, we can create a relationship between tables even if the relationship does not exist between the tables in the dataset by using XML designer.

Solutions: Just A Minute


1. Ans: Identify the two types of data providers and list the difference between them? The two types of data providers are SQL data provider and OLEDB data provider. The OLEDB data provider works with all the OLE DB providers, such as SQL OLE DB provider, Oracle OLE DB provider, and Jet OLE DB provider, whereas the SQL data provider is used to work specifically with Microsoft SQL Server.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 47

System.Object,ByVal e As System.EventArgs) Handles cmdCheckdata.Click If Val(txtd_join.Text) = 0 Then txtd_join.Text = CType(Today, Date) testdate = CType(Today, Date) cmdSave.Enabled = True Else testdate = CType(txtd_join.Text, Date) If (testdate < Today) Or (testdate > Today) Then MessageBox.Show("The entered date is not valid. The Date cannot be less than or greater than the current date.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub Else testdate = CType(Today, Date) cmdSave.Enabled = True End If End If End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdSave.Enabled = False cmdGet.Enabled = False End Sub End Class

46 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdSave.Enabled = False cmdGet.Enabled = False cmdReset.Enabled = False End Sub End Class

Solution: Additional Exercise 4.A.1


Public Class Emp Public empDate As Date End Class Public Class Form1 Inherits System.Windows.Forms.Form Dim testdate As Date Dim EmpObject As New Emp() Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click EmpObject.empDate = testdate cmdGet.Enabled = True End Sub Private Sub cmdGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGet.Click

lbl_date.Text= CType(EmpObject.empDate, Date) End Sub

Private Sub cmdCheckData_Click(ByVal sender As

NIIT

Programming in Visual Basic .NET-Coordinator Guide 45

End Sub Public Sub Data_Check(ByVal e As String) Dim x As Integer Dim y As String Dim z As Boolean x = Len(e) y = Mid(e, 1, 1) z = Val(Mid(e, 2, 3)) If x <> 4 Or y <> "E" Or z <> True Then MessageBox.Show("The entered data is not valid. The Employee ID should start with the letter E followed by three digits.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" txteid.Clear() Else k = "n" j = "not ok" End If End Sub Public Sub Data_Check(ByVal e_age As Integer) If e_age < 21 Or e_age > 60 Then MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" txtage.Clear() Else j = "ok" End If End Sub

44 Programming in Visual Basic .NET-Coordinator Guide

NIIT

End If If Val(txtsalary.Text) < 10000 Or Val(txtsalary.Text) > 60000 Then MessageBox.Show("The entered data is not valid. The salary cannot be less than 10000 and greater than 60000.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" Exit Sub End If If Val(txtd_join.Text) = 0 Then txtd_join.Text = CType(Today, Date) testdate = CType(Today, Date) Else testdate = CType(txtd_join.Text, Date) If (testdate < Today) Or (testdate > Today) Then MessageBox.Show("The entered date is not valid. The Date of Joining cannot be less than or greater than the current date.", "Data Entry Error ", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" Exit Sub Else testdate = CType(Today, Date) End If End If If j = "ok" And k = "n" Then MessageBox.Show("Thank you for entering the employee details!", "Congratulations!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) cmdSave.Enabled = True cmdGet.Enabled = True cmdReset.Enabled = True End If

NIIT

Programming in Visual Basic .NET-Coordinator Guide 43

lble_id.Text = "E_ID" lblf_name.Text = "FName" lbll_name.Text = "LName" lbl_add.Text = "Address" lbl_age.Text = "Age" lbl_dateofjoining.Text = "D_join" lbl_dept.Text = "Dept." lbl_salary.Text = "Salary" cmdSave.Enabled = False cmdGet.Enabled = False cmdReset.Enabled = False End Sub Private Sub cmdCheckData_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles cmdCheckdata.Click Data_Check(txteid.Text) If k = "yes" Then Exit Sub End If i = Len(txtage.Text) If i = 0 Then MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) ElseIf Val(txtage.Text) <> 0 Then i = CType(txtage.Text, Integer) Call Data_Check(i) Else MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

42 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Private Sub cmdGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGet.Click lble_id.Text = MyNewClass.eid lblf_name.Text = MyNewClass.fname lbll_name.Text = MyNewClass.lname lbl_add.Text = MyNewClass.address lbl_age.Text = MyNewClass.age lbl_dateofjoining.Text = MyNewClass.Date_of_joining lbl_dept.Text = MyNewClass.Department lbl_salary.Text = MyNewClass.salary End Sub Private Sub cmdReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReset.Click MyNewClass.eid = "" MyNewClass.fname = "" MyNewClass.lname = "" MyNewClass.address = "" MyNewClass.age = 0 MyNewClass.Date_of_joining = Today MyNewClass.Department = "" MyNewClass.salary = 0 txteid.Clear() txtfname.Clear() txtlname.Clear() txtaddress.Clear() txtage.Clear() txtdept.Clear() txtd_join.Clear() txtsalary.Clear()

NIIT

Programming in Visual Basic .NET-Coordinator Guide 41

UGP 2
Public Class Employee Public eid As String = "" Public fname As String = "" Public lname As String = "" Public address As String = "" Public age As Integer = 0 Public Date_of_joining As Date Public Department As String = "" Public salary As Integer = 0 End Class Public Class frmEmployeedetails Inherits System.Windows.Forms.Form Dim MyNewClass As New Employee() Dim i As Integer = 0 Dim j As String = "ok" Dim k As String = "yes" Dim testdate As Date Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click MyNewClass.eid = txteid.Text MyNewClass.fname = txtfname.Text MyNewClass.lname = txtlname.Text MyNewClass.address = txtaddress.Text MyNewClass.age = txtage.Text MyNewClass.Date_of_joining = testdate MyNewClass.Department = txtdept.Text MyNewClass.salary = txtsalary.Text End Sub

40 Programming in Visual Basic .NET-Coordinator Guide

NIIT

ByVal e As System.EventArgs) Handles cmdReset.Click OrderObject.I_no = "" OrderObject.O_date = Today OrderObject.C_id = "" OrderObject.P_id = "" OrderObject.Cost = 0 OrderObject.Advance = 0 txtino.Clear() txtdate.Clear() txtcid.Clear() txtpid.Clear() txtcost.Clear() txtadvance.Clear() lbli_no.Text = "I_No" lbl_date.Text = "Date" lblc_id.Text = "C_ID" lblp_id.Text = "P_ID" lbl_cost.Text = "Cost" lbl_advance.Text = "Advance" cmdSave.Enabled = False cmdGet.Enabled = False cmdReset.Enabled = False End Sub Private Sub frmOrderdetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdSave.Enabled = False cmdGet.Enabled = False cmdReset.Enabled = False End Sub End Class

NIIT

Programming in Visual Basic .NET-Coordinator Guide 39

txtino.Clear() Exit Sub End If If Val(txtcost.Text) = 0 Or Val(txtcost.Text) < 0 Then MessageBox.Show("The entered data is not valid. Cost cannot be zero or negative.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtcost.Clear() Exit Sub End If If Val(txtadvance.Text) < 0 Then MessageBox.Show("The entered data is not valid. Advance cannot be negative.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtadvance.Clear() Exit Sub End If If Val(txtcost.Text) < Val(txtadvance.Text) Then MessageBox.Show("The entered data is not valid. Advance cannot be more than the cost.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtadvance.Clear() Exit Sub End If If Val(txtdate.Text) = 0 Then txtdate.Text = CType(Today, Date) End If cmdSave.Enabled = True cmdGet.Enabled = True cmdReset.Enabled = True End Sub

Private Sub cmdReset_Click(ByVal sender As System.Object,

38 Programming in Visual Basic .NET-Coordinator Guide

NIIT

OrderObject.Advance = Val(txtadvance.Text) End Sub Private Sub cmdGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGet.Click lbli_no.Text = OrderObject.I_no lbl_date.Text = CType(OrderObject.O_date, Date) lblc_id.Text = OrderObject.C_id lblp_id.Text = OrderObject.P_id If OrderObject.Cost = 0 Then lbl_cost.Text = 0 Else lbl_cost.Text = OrderObject.Cost End If If OrderObject.Advance = 0 Then lbl_advance.Text = 0 Else lbl_advance.Text = OrderObject.Advance End If End Sub Private Sub cmdCheckdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCheckdata.Click Dim x, z As Integer Dim y As String x = Len(txtino.Text) z = Val(Mid(txtino.Text, 2, 3)) y = Mid(txtino.Text, 1, 1) If x <> 4 Or y <> "I" Or z = 0 Then MessageBox.Show("The entered data is not valid. The Invoice number should start with the letter I followed by three digits.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

NIIT

Programming in Visual Basic .NET-Coordinator Guide 37

The details of controls for displaying the customer details retrieved from the memory variables are listed in the following table:
Control For Invoice Number Date Customer ID Product ID Cost Advance Control Type Label Label Label Label Label Label Control Name lbli_no lbl_date lblc_id lblp_id lbl_cost lbl_advance I_No Date C_ID P_ID Cost Advance Control Text

The Order class should be declared as given below: Public Class Order Public I_no As String = "" Public O_date As Date Public C_id As String = "" Public P_id As String = "" Public Cost As Integer = 0 Public Advance As Integer = 0 End Class The code that implements the required checks is given below: Public Class frmOrderdetails Inherits System.Windows.Forms.Form

Dim OrderObject As New Order()

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click OrderObject.I_no = txtino.Text OrderObject.O_date = txtdate.Text OrderObject.C_id = txtcid.Text OrderObject.P_id = txtpid.Text OrderObject.Cost = txtcost.Text

36 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Save the project by selecting the Save All option from the File menu. 1. 2. Select Start from the Debug menu, or press F5. Fill in the employee details in the relevant text boxes. You can also enter invalid data for employee id and telephone number intentionally to validate the checks that you have applied for the Employee data entry screen. If any error message appears on the screen, read the message and re-enter values in the relevant text boxes. Use the Save, Get, and Reset buttons to verify the correct working of the code.

3. 4.

Solution: Unguided Practice UGP 1


The details of controls to accept data on the Order Details form are listed in the following table:
Control For Control Type Label Invoice Number TextBox Label Date TextBox Label Customer ID TextBox Label Product ID TextBox Label Cost TextBox Label Advance TextBox txtadvance txtcost lbladvance Advance txtpid lblcost Cost txtcid lblpid Product ID txtdate lblcid Customer ID txtino lbldate Date lblino Control Name Control Text Invoice Number

The details of controls for storing data in and retrieving data from memory variables are listed in the following table:
Control For Saving entered data Fetching data from memory variables Validating entered data Clearing contents of the TextBoxes Control Type Button Button Control Name cmdSave cmdGet Save Get Control Text

Button Button

cmdCheckdata cmdReset

Check Data Reset

NIIT

Programming in Visual Basic .NET-Coordinator Guide 35

If x <> 4 Or y <> "E" Or z <> True Then MessageBox.Show("The entered data is not valid. The Employee ID should start with the letter E followed by three digits.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" txteid.Clear() Else k = "n" j = "not ok" End If End Sub Public Sub Data_Check(ByVal e_age As Integer) If e_age < 21 Or e_age > 60 Then MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) j = "not ok" txtage.Clear() Else j = "ok" End If End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cmdSave.Enabled = False cmdGet.Enabled = False cmdReset.Enabled = False End Sub End Class

34 Programming in Visual Basic .NET-Coordinator Guide

NIIT

If k = "yes" Then Exit Sub End If i = Len(txtage.Text) If i = 0 Then MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) ElseIf Val(txtage.Text) <> 0 Then i = CType(txtage.Text, Integer) Call Data_Check(i) Else MessageBox.Show("The entered data is not valid. The Employee age cannot be less than 21 and greater than 60.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End If If j = "ok" And k = "n" Then MessageBox.Show("Thank you for entering the employee details!", "Congratulations!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) cmdSave.Enabled = True cmdGet.Enabled = True cmdReset.Enabled = True End If End Sub Public Sub Data_Check(ByVal e As String) Dim x As Integer Dim y As String Dim z As Boolean x = Len(e) y = Mid(e, 1, 1) z = Val(Mid(e, 2, 3))

NIIT

Programming in Visual Basic .NET-Coordinator Guide 33

e As System.EventArgs) Handles cmdReset.Click MyNewClass.eid = "" MyNewClass.fname = "" MyNewClass.lname = "" MyNewClass.address = "" MyNewClass.age = 0 MyNewClass.Date_of_joining = Today MyNewClass.Department = "" MyNewClass.salary = 0 txteid.Clear() txtfname.Clear() txtlname.Clear() txtaddress.Clear() txtage.Clear() txtdept.Clear() txtd_join.Clear() txtsalary.Clear() lble_id.Text = "E_ID" lblf_name.Text = "FName" lbll_name.Text = "LName" lbl_add.Text = "Address" lbl_age.Text = "Age" lbl_dateofjoining.Text = "D_join" lbl_dept.Text = "Dept." lbl_salary.Text = "Salary" End Sub Private Sub cmdCheckdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCheckdata.Click Data_Check(txteid.Text)

32 Programming in Visual Basic .NET-Coordinator Guide

NIIT

MyNewClass.Date_of_joining = testdate End If MyNewClass.Department = txtdept.Text If Val(txtsalary.Text) = 0 Then MyNewClass.salary = 0 Else MyNewClass.salary = txtsalary.Text End If End Sub Private Sub cmdGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGet.Click lble_id.Text = MyNewClass.eid lblf_name.Text = MyNewClass.fname lbll_name.Text = MyNewClass.lname lbl_add.Text = MyNewClass.address If MyNewClass.age = 0 Then lbl_age.Text = "" Else lbl_age.Text = MyNewClass.age End If lbl_dateofjoining.Text = MyNewClass.Date_of_joining lbl_dept.Text = MyNewClass.Department If MyNewClass.salary = 0 Then lbl_salary.Text = "" Else lbl_salary.Text = MyNewClass.salary End If End Sub Private Sub cmdReset_Click(ByVal sender As System.Object, ByVal

NIIT

Programming in Visual Basic .NET-Coordinator Guide 31

Public fname As String = "" Public lname As String = "" Public address As String = "" Public age As Integer = 0 Public Date_of_joining As Date Public Department As String = "" Public salary As Integer = 0 End Class Public Class frmEmployeedetails Inherits System.Windows.Forms.Form Dim MyNewClass As New Employee() Dim MyNewClass As New Employee() Dim i As Integer = 0 Dim j As String = "ok" Dim k As String = "yes" Dim testdate As Date = #6/12/2001# 'This is a sample date to be used when no date is entered.

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click MyNewClass.eid = txteid.Text MyNewClass.fname = txtfname.Text MyNewClass.lname = txtlname.Text MyNewClass.address = txtaddress.Text MyNewClass.age = txtage.Text If Val(txtd_join.Text) = 0 Then MyNewClass.Date_of_joining = testdate Else testdate = CType(txtd_join.Text, Date)

30 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Eight member variables need to be declared in the Employee class. The data type of each variable is listed in the following table:
Variables eid fname lname address Age Date_of_joining Department Salary String String String String integer Date String integer Data type Employee ID First Name Last Name Address Age Dateofjoining Dept Salary To hold value for

You can use the Visual Studio .NET IDE to create the user interface screen. To create the user interface screen, you need to perform the following steps: 1. 2. 3. 4. 5. 6. 7. 8. 9. Start Microsoft Visual Studio .NET using the Start menu. Select the Project option from the New submenu under the File menu. Ensure that in the New Project dialog box, Project Types is Visual Basic Projects and Template is Windows Application. Type Employee_details in the Name text box and click the OK button. Right-click the Form1.vb form in the Solution Explorer window and select the Properties option to display the Properties window. Click the Form1.vb form in the design viewer and set the Name property as frmEmployeeDetails and Text property as Employee Details by using the Properties window. In the Solution Explorer window, right-click the Employee_details project and select the Properties option. Select frmCustomerdetails as the startup object from the Startup object drop-down list and click the OK button. Add the required controls from the Toolbox and specify a name for the controls using the Properties window. Organize the controls.

Since the requirement specified in the problem statement is to display error messages when incorrect data is entered for employee id and age, you need to use either the Msgbox function or the Show() method of the MessageBox class to display error messages. Since MessageBox class offers better user interface, you will use the MessageBox class to display appropriate error messages. The entire code for this practice is given in the following code: Public Class Employee Public eid As String = ""

NIIT

Programming in Visual Basic .NET-Coordinator Guide 29

Control For

Control Type TextBox Label

Control Name txtdept lblsalary txtsalary Salary

Control Text

Salary TextBox

The details of controls for storing data in and retrieving data from memory variables are listed in the following table:
Control For Saving entered data Fetching data from memory variables Control Type Button Button Control Name cmdSave cmdGet Save Get Control Text

To allow users to check for the validity of the data entered, you need to invoke the Check_data() procedure. It is important that until the data is validated and found correct, the users should not be able to access the Save and Get buttons on the frmEmployeeDetails form. Therefore, you need to initially disable the Save and Get buttons. However, to allow users to invoke the Check_data() procedure, you need to add a command button to the frmEmployeeDetails form. You can then call the Check_data () procedure from the Click event of the newly added Check Data button. Again, since there should be a provision for clearing the details of last employee details entered, you should include another button to the frmEmployeeDetails form. Since this button will be used for clearing the content of the text boxes on the frmEmployeeDetails form, you can name the button as Reset. The following table recommends suitable prefixes that you can use for the two buttons:
Control For Validating entered data Clearing contents of the TextBoxes Control Type Button Button Control Name cmdCheckdata cmdReset Control Text Check Data Reset

The details of controls for displaying the employee details retrieved from memory variables are listed in the following table:
Control For Employee ID First Name Last Name Address Age Date of Joining Department Salary Control Type Label Label Label Label Label Label Label Label Control Name lble_id lblf_name lbll_name lbl_add lbl_age lbl_dateofjoining lbl_dept lbl_salary E_ID Fname Lname Address Age Dateofjoining Dept Salary Control Text

28 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click PageSetupDialog1.PageSettings = PgSettings PageSetupDialog1.ShowDialog() End Sub End Class Ans: Import System.Drawing.Printing using the Imports keyword.

Solution: Guided Practice 4.P.1


As per the problem statement, the employee data entry application must check the validity of the employee id and age. You can add the provision for checking valid employee id and age by including procedures in the employee data entry application. Since Visual Basic .NET allows the use of procedure overloading, while adding procedures to the employee data entry application, you can create two versions of the same procedure to check the validity of the employee id and age. You will create an overloaded procedure for checking the validity of employee id and age. You can name the procedure as Check_data(). To accept employee details, you need to add controls to the frmEmployeeDetails form. The details of controls to accept data on the Employee Details form are listed in the following table:
Control For Control Type Label Employee ID TextBox Label First Name TextBox Label Last Name TextBox Label Address TextBox Label Age TextBox Label Date of Joining TextBox Department Label txtd_join lbldept Department txtage lbld_join Date of joining txtaddress lblage Age txtlname lbladdress Address txtfname lbllname Last Name txteid lblfname First Name lbleid Control Name Control Text Employee ID

NIIT

Programming in Visual Basic .NET-Coordinator Guide 27

Dim Annual_Salary As Integer = 150000 Dim months As Integer = 12 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Monthly_Salary = Calculate_Average(Annual_Salary, months) Label1.Text = "The salary earned per month is: " & Monthly_Salary End Sub Public Function Calculate_Average(ByVal asalary As Integer, ByVal mnths As Integer) As Integer asalary = asalary / mnths Return asalary End Function End Class Ans: The text The salary earned per month is: 12500 will be displayed as the text for Label1. 4. What will be the output of the following code when Button1 is clicked at run time? Public Class Form1 Inherits System.Windows.Forms.Form Dim FDialog As New FontDialog() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1 = FDialog.Font End Sub End Class Ans: The code will not display any output. Since the ShowDialog() method of the FontDialog class is not called, the Font dialog box will not be displayed. Therefore, you cannot change the font style, size, and effect. 5. The following code snippet is written in the Code Editor window of Form1. There is one PageSetupDialog control added to the form. While building the project, there was a build error. What would you do to resolve the error? Public Class Form1 Inherits System.Windows.Forms.Form Dim PgSettings As New PageSettings()

26 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Optional ByVal Amount As Single = 10) Label1.text = CustAcct Label2.text = Amount End Sub End Class Ans: The numbers 18 and 12 will be displayed as the text of the two labels on the form. 2. There are two labels named Label1 and Label2 and one button named Button1 on the form, Form1. You have created a user-defined Sub procedure called MySub to process information when the user clicks the Button1. Predict the output of the following code when the program is executed. Public Class Form1 Inherits System.Windows.Forms.Form

Dim j As Integer Private Sub MySub(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click j = Item_Status("I60", 90) Label2.Text = "The units sold is: " & j End Sub Public Function Item_Status(ByVal ItemCode As String, ByVal Amount As Single) As Integer Amount = Amount + 90 Label1.Text = "For the Item Code: " & ItemCode Return Amount End Function End Class Ans: The Text For the Item Code: I60 will be displayed as the text for Label1, and the text The units sold is: I80 will be displayed as the text for Label2. 3. There is a label named Label1 and a button named Button1 on the form, Form1. The following code is added in the Code Editor window of Form1. What will be the output of the program when Button1 is clicked at run time? Public Class Form1 Inherits System.Windows.Forms.Form Dim Monthly_Salary As Integer

NIIT

Programming in Visual Basic .NET-Coordinator Guide 25

Set (ByVal Value As Integer) readwriteproperty=Value End Set End Property End Class

Adding classes to a Visual Basic .NET application


It is important to note that you can define a class either by adding the class definition in the Code Editor window of the Form or by selecting Add Class option. You can access the Add Class option either from the Project menu or by right-clicking the project name in the Solution Explorer window and selecting Add Class option from the Add menu. If you create a class by using the Add Class option, Visual Basic .NET stores the class definition in a separate .vb file. However, if you define a class in the Code Editor window of a form, the definition is added to the code for the form and no separate .vb file is created. You can explicitly specify this information to students for their better understanding. To show you the distinction, the Employee class definition is added to the Code Editor window of the frmEmployeedetails form as shown in the following code.

FAQ
1. What is the difference between procedures in Visual Basic .NET and earlier versions of Visual Basic?

Ans: In earlier versions parenthesis was not required for procedures or functions that did not take any parameters. In Visual Basic .NET, a parenthesis is required even if a procedure or function does not take any parameters. Also, in Visual Basic .NET, all values are passed by default by value. Another difference is that optional parameters must have a default value.

Solutions: Just a Minute


1. There are two labels named Label1 and Label2 and one button named Button1 on the form, Form1. Predict the output of the following code, when the Button1 is clicked at run time. Public Class Form1 Inherits System.Windows.Forms.Form Dim i As Integer = 18 Dim s As Single = 12 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Call Check_Acct_Status(i, s) End Sub

Public Sub Check_Acct_Status(ByVal CustAcct As Integer,

24 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Encourage students to find out information about particular functions. Discussing all the functions is not possible within the allocated time. Searching for information will also help students to learn on their own. Using dialog classes will be a comparatively new concept for students. As first part of this lesson will take less time, you can describe dialog boxes in details.

Additional Input
Properties
To make a property read-only or write-only, declare it as shown below: [Access Specifier] [ReadOnly|WriteOnly] Property PropertyName ([parameters]) As Type You must create a read-only property if you do not want others to change that property. Similarly, you can create a write-only property if you do not want others to read a property. The following is an example of the code that has all the three properties: read-only, write-only, and read/write. Class PropertyDemo Private readproperty As Integer Private writeproperty As Integer Private readwriteproperty As Integer Public ReadOnly Property ReadOnlyProperty() As Integer Get Return readproperty End Get End Property Public WriteOnly Property WriteOnlyProperty () As Integer Set (ByVal Value As Integer) writeproperty = Value End Set End Property

Public Property ReadAndWriteProperty () As Integer Get Return readwriteproperty End Get

NIIT

Programming in Visual Basic .NET-Coordinator Guide 23

After the base form is designed, you can create the inherited form, BaseForm. However, to create an inherited form, you first need to build the application. You build the application by selecting the Build option from the Build menu. After you have performed the prerequisite task of building the application, you need to add an inherited form to the project. You add an inherited form by selecting the Add Inherited Form option from the shortcut menu. 1. 2. In the Solution Explorer window, right-click the project name. Select the Add Inherited Form option under the Add shortcut menu.

Selecting the Add Inherited Form option displays the Add New Item dialog box. In the Add New Item dialog box, specify the name of the inherited from as Query_Handling_Form and click the Open button. Next, you need to specify the component from which you want to inherit the form in the Inheritance Picker dialog box. Select the component named BaseForm and click the OK button. After adding an inherited form to the project, you need to add a label to the inherited form to distinguish it from the base form. Add a label with the text The Inherited Form is Displayed to Query_Handling_Form. 1. Add a label to the inherited form as planned.

After adding the label to the Query_Handling_Form, you need to change the startup object to Query_Handling_Form. 1. 2. 3. In the Solution Explorer window, right-click the Inherited_Form label and select the Properties command. In the Inherited_Form Property Pages dialog box, select Query_Handling_Form as the Startup object from the drop-down list box. Click the OK button.

Save the project by selecting the Save All option from the File menu. Select the Start option from the Debug menu, or press F5. To exit the Visual Basic .NET application, select the Stop Debugging option from the Debug menu.

Lesson Four
Experiences
You should compare the procedures in Visual Basic .NET with the methods and functions in Java. You do not need to go into details because students already know about methods. However, emphasize the fact that Visual Basic .NET has two types of procedures, Sub and Functions. While Function procedures return a value, Sub procedures do not return any value. Then, describe the syntax for both the types. You can illustrate the concept using examples given in the text book. Then, describe the different types of procedures. While describing parameter array tell students about its importance. Before starting with overloading, remind students about method signature and method overloading that they learned in C++ and Java. Show them an example of procedure overloading in Visual Basic .NET.

22 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Since all the data entry forms will have the Add, Modify, Delete, Reset and Exit buttons, you need to design the user interface of the base form using these five buttons. You also need to specify the text and the name of the form and the buttons on the form. To provide a meaningful name to the form, set the Name property of the form to BaseForm and the Text property to Data Entry Form.
Control For Adding records to the Query Handling database Modifying records of the Query Handling database Deleting records from the Query Handling database Resetting the values in the other controls on the form Exiting the application Control Type Command Button Control Name cmdAdd Add Control Text

Command Button

cmdModify

Modify

Command Button

cmdDelete

Delete

Command Button

cmdReset

Reset

Command Button

cmdExit

Exit

Since you need to verify that the Query_Handling_Form is displayed, you should plan to add a label to the Query_Handling_Form.
Control For Displaying a message Control Type Label Control Name Label1 Control Text The Inherited Form is Displayed

Perform the necessary tasks to create the user interface based on the requirements. You can use the Visual Studio IDE to create the user interface screen. 1. 2. 3. Start Microsoft Visual Studio .NET 7.0. Select the Project command from the New submenu under the File menu. Ensure that in the New Project dialog box, the Project Types is Visual Basic Projects and the Template is Windows Application. Type Inherited_Form in the Name text box and click the OK button. Click the Solution Explorer button on the Toolbar to display the Solution Explorer window. Right-click Form1.vb in the Solution Explorer window and select the Properties option to display the Properties window. Click the form in the Windows Form designer and set the Name and Text properties of the form in the Properties window, as planned. In the Solution Explorer window, right-click the Inherited_Form.vb and select the Properties command from the shortcut menu. Select BaseForm as the startup object from the Startup object drop-down list and click the OK button. Add the required controls from the Toolbox and name them, as planned.

4. 5. 6. 7. 8. 9.

10. Organize the controls, as planned.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 21

num = num * num * num End Sub Shadows Sub display() MsgBox("The value stored in the num variable is: " & num) End Sub End Class It is important to note that shadowing is different from Overriding since in overriding, you implement polymorphism by defining different implementation of a procedure using the same calling sequence.

Solutions: Just a Minute


1. Why is a structure called a composite data type?

Ans: A structure is called a composite data type because within a structure you can define variables of varied data types, such as integer, string, single, double, date, and object. 2. Identify the syntactical error in the following declaration of an interface:

Interface IProductdetails Property ProductName() As String Sub UpdateCustStatus() Label1.text = This is a Sub Procedure to check the status of the Product End Sub Event Update_Complete() End Interface Ans: You cannot write the implementation steps of a Sub procedure within the declaration of an interface. 3. How are interfaces different from abstract classes?

Ans: All the methods in an interface have to be abstract and cannot have implementation code, whereas an abstract class might contain a method that has a body.

Solution: Guided Practice 3.P.1


Since the requirement stated in the problem statement is to create a similar user interface for all the data entry forms, you can create a base form that has the Add, Modify, Delete, Reset and Exit buttons on it. You can then inherit all of the data entry forms from the base form.

20 Programming in Visual Basic .NET-Coordinator Guide

NIIT

the button. You also call the sqr()and the display() method of the derived class. If you execute the code and click the Button Button1, you get a message box that displays the calculated value of the number stored in the variable num. However, if you add a Sub procedure with the same name display() to the base class class1, the derived class class2 throws a build error that states that the Sub procedure name conflicts with the base class procedure name. To protect the derived class class2 from throwing such build errors, you need to use the shadowing concept and declare the display() method in the derived class with the shadows keyword as shown below: Public Class Form1 Inherits System.Windows.Forms.Form

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim c2 As New class2() c2.sqr() c2.display()

End Sub End Class

Public Class class1 Public num As Integer = 9 Public Sub sqr() num = num * num End Sub Public Sub display() MsgBox("The value stored in the num variable is: " & num) End Sub End Class Public Class class2 Inherits class1 Public Sub cube()

NIIT

Programming in Visual Basic .NET-Coordinator Guide 19

defined in the derived class. In Visual Basic .NET, you implement shadowing by using the Shadows keyword. The following examples illustrate when you will use the shadowing concept: Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim c2 As New class2() c2.sqr() c2.display() End Sub End Class Public Class class1 Public num As Integer = 9 Public Sub sqr() num = num * num End Sub End Class

Public Class class2 Inherits class1 Public Sub cube() square = num * num * num End Sub Public Sub display() MsgBox("The value stored in the num variable is: " & num) End Sub End Class In the above example, you create a class called class1. In class1, you define a Sub procedure to calculate the square of the value stored in the variable num. Next, you inherit a class called class2 from class1. In class2, you add a Sub procedure to calculate the cube of the value stored in the variable num and another Sub procedure called display() to display the calculated value stored in num. Next, you add a button to the form Form1 and declare an object of class2 in the click event of

18 Programming in Visual Basic .NET-Coordinator Guide

NIIT

cbCompDrome.Checked = False cmbCourse.Text = "" lstTimeSlot.SelectedIndex = 0 End If 7. In the event handler for the Click event of the Close button, type the following code: Close() 8. Select Debug Start to execute the application.

Lesson Three
Experiences
Start this lesson by asking questions on the object-oriented programming (OOP) concepts that students learned in the first semester. Keep the question-answer session brief. Then, establish a connect between the OOP concepts and Visual Basic .NET. You can also tell students that previous versions of Visual Basic were object-based they supported objects but did not support direct inheritance. Emphasize that Visual Basic .NET is an object-oriented language similar to C++ and Java. Explain structures in brief. Explain the similarities and differences between a class and a structure without going into details. Remember that students have learned about structures in C++ in the first semester. Students have used interfaces in Java. Therefore, ask students to recollect the concepts of interface and then explain the syntax for declaring and using an interface in Visual Basic .NET. You need not go into details. In addition, inform students that they will learn to implement polymorphism using interfaces in Lesson 13. While teaching students interfaces, distinguish between an interface and user interface to avoid any confusion between the two. You can simply tell students that an interface is a blueprint for the purpose of enforcing functionalities in inherited classes and user interfaces allow interaction between a user and an application. A namespace is a new concept introduced in Visual Basic .NET. Students should use namespaces and they should understand the importance of namespaces. You can compare namespaces with the concept of packages in Java. Tell students that it is good practice to organize classes into a hierarchy. While discussing events compare the way events are handled in Java and Visual Basic .NET.

Additional Input
Multicast Delegates
Some delegates, called multicast delegates, maintain a list of references to multiple functions. The signatures of all the functions referenced by a multicast delegate need to be the same.

Shadowing
In Visual Basic .NET, you can use the shadowing concept to protect a derived class from throwing build errors when the base class is modified to include a member, such as a procedure, that has already been

NIIT

Programming in Visual Basic .NET-Coordinator Guide 17

6.

In the event handler for the Click event of the OK button, type the following code: Dim Gender As String Dim Course As String Dim TimeSlot As String Dim Facilities As String If txtName.Text = "" Or txtAge.Text = "" Or txtAddress.Text = "" or cmbCourse.Text = "" Then MsgBox("Please enter all details") Else If rbMale.Checked Then Gender = "Male" ElseIf rbFemale.Checked then Gender = "Female" End If Course = cmbCourse.SelectedItem.ToString TimeSlot = lstTimeSlot.SelectedItem.ToString If cbLibrary.Checked Then Facilities = "Library " End If If cbCompDrome.Checked Then Facilities = Facilities & " Computer Drome" End If MsgBox("Name: " + txtName.Text + " Age: " + txtAge.Text + " Address: " + txtAddress.Text + " Gender: " + Gender + " Course: " + Course + " Time slot: " + TimeSlot + " Facilities : " + Facilities) txtName.Text = "" txtAge.Text = "" txtAddress.Text = "" rbMale.Checked = False rbFemale.Checked = False cbLibrary.Checked = False

16 Programming in Visual Basic .NET-Coordinator Guide

NIIT

To create the Student form, perform the following steps: 1. 2. 3. Select Project Add Windows Form. In the Add New Item dialog box, specify the name of the form as Student.vb. Click the Open button. Design the form and set the Name property of various controls, as shown below:

txtName txtAge txtAddress rbMale rbFemale cmbCourse lstTimeSlot

cbLibrary cbCompDrome btnOk 4. 5. Set the MultiLine property of txtAddress to true. Double-click the form and type the following code in the Student_Load() method: cmbCourse.Items.Add("Web Application Developer") cmbCourse.Items.Add("Database Administrator") cmbCourse.Items.Add("Network Administrator") cmbCourse.Items.Add("Windows Application Developer") lstTimeSlot.Items.Add("7:00-9:00") lstTimeSlot.Items.Add("9:00-11:00") lstTimeSlot.Items.Add("11:00-1:00") lstTimeSlot.Items.Add("1:00-3:00") lstTimeSlot.Items.Add("3:00-5:00") lstTimeSlot.SelectedIndex = 0 btnClose

NIIT

Programming in Visual Basic .NET-Coordinator Guide 15

Solution: Unguided Practice UGP 1


1. Select File New Project. This opens the New Project dialog box. In the Project Types pane, select Visual Basic Projects. In the Templates pane, select Windows Application. Name the application 2_UGP_1 and click the OK button. In the Windows Form, create two Label controls and set their Text property to Username and Password, respectively. Create two TextBox controls. Change the Name property of the TextBox controls to txtUserName and txtPassword respectively. Set the PasswordChar property of txtPassword to *. Create a Button control and set its Text property to OK. Create a Label control to display the error message. Set the Name property of the Label control to lblMessage. In the Form1 class, declare a variable called ctr by using the following statement: Dim Ctr as Integer 7. Double-click the OK button. In the event handler, type the following code: Dim LoginName As String, Password As String LoginName = txtUserName.Text Password = txtPassword.Text Ctr = Ctr + 1 If LoginName = "Adminuser" And Password = "admin" Then Dim frmObj As New Student() frmObj.Show() Else If Ctr < 3 Then lblMessage.Text = "Incorrect User Name or Password Please Try again" txtUserName.Focus() Else MsgBox("Unauthorized Access. Aborting...") Close() End If End If

2. 3.

4. 5. 6.

14 Programming in Visual Basic .NET-Coordinator Guide

NIIT

2.

In the Windows Form, create six Label controls and set their Text property as shown in the following table:
Label Label1 Label2 Label3 Label4 Label5 Label6 Order Number Order Date Customer ID Product ID Cost Advance Text

3.

Create five TextBox controls and a ComboBox control. Set the Name property of the TextBox controls to txtOrderNo, txtOrderDate, txtCustID, txtCost, and txtAdvance. Set the Name property of the ComboBox control to cmbProdID. Create a Button control and set its Text property to Save. Double-click the form and type the following code in the Load event of the form to add items in the ComboBox control: cmbProdID.Items.Add("P001") cmbProdID.Items.Add("P002") cmbProdID.Items.Add("P003") cmbProdID.Items.Add("P015")

4. 5.

6.

Type the following code in the Click event of the Button control: If txtOrderNo.Text = "" Or txtOrderDate.Text = "" Or txtCustID.Text = "" Or cmbProdID.Text = "" Or txtCost.Text = "" Or txtAdvance.Text = "" Then MsgBox("Please enter all details") Else MsgBox("Saved Data") End If

7.

Select Debug Start to start the application and check whether the application works as per the requirements.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 13

Solutions: Just a Minute


1. Ans: Dim ctr as Integer for ctr=1 to 100 If ctr mod 2 <> 0 Then Msgbox (ctr) End If Next 2. Ans: Dim X As Char X = "a" If X = "a" Or X = "e" Or X = "i" Or X = "o" Or X = "u" Then MsgBox("Vowel") Else MsgBox("Not a Vowel") End If 3. Ans: Dim Form2obj as New Form2() Form2obj.show() You have created two forms named Form1 and Form2. Write the code so that when a user clicks the OK button in Form1, Form2 should be displayed. Write the construct to check whether the character stored in the variable X is a vowel and display an appropriate message. Write a loop structure to display all odd numbers between 1 and 100.

Solution: Guided Practice 2.P.1


1. Select File New Project. This opens the New Project dialog box. In the Project Types pane, select Visual Basic Projects. In the Templates pane, select Windows Application. Name the application as 2_P_1 and click the OK button.

12 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Additional Inputs
Demos
The demo for this lesson is stored in the Solutions\Lesson2\2.D.1 folder.

The Static Keyword


The variables that are local to a procedure are destroyed after all the statements in the procedure are executed. However, in several cases, you need to preserve the value of a variable after the procedure has been executed. This is especially useful if you need to know the number of times a procedure has been called. To do so, you can declare a variable by using the Static keyword inside the procedure. The value of a variable declared as Static is maintained across procedure calls. Thus, you can increment the variable to maintain a count of the number of times the procedure has been executed.

Comparing Visual Basic 6.0 and Visual Basic .NET Language Features
If students know Visual Basic 6, you can also discuss some major language changes. State that while earlier versions of Visual Basic were targeted at Microsoft Windows client applications, Visual Basic .NET is intended for creating Web applications as well. For this purpose, Visual Basic .NET generates managed code for the Common Language Runtime. This entails changes to the language itself. Some of the language feature changes are listed below:

In Visual Basic 6, you could create a fixed-length string by using a statement given below:
Dim str as string * 30 However, in Visual Basic .NET, you cannot declare a string to have a fixed length. Therefore, the above example would display an error.

Another major change is in the way in which the ReDim keyword is used. In Visual Basic 6.0, the
ReDim keyword could be used in the initial declaration of the array. However, in Visual Basic .NET, ReDim cannot be used to declare an array. You must first use the Dim keyword to declare an array and then use the ReDim keyword if you want to resize the array.

The Variant data type that was available in Visual Basic 6.0 is no longer supported in Visual Basic
.NET.

The Wend keyword of Visual Basic 6.0 is replaced with the End While keyword in Visual Basic
.NET.

FAQs
1. Which data type can be used in a Visual Basic .NET application as a replacement of the Variant data type provided in Visual Basic 6.0?

Ans: The Variant data type of Visual Basic 6.0 can be replaced with the Object data type in Visual Basic .NET.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 11

Ans: Managed code is the code that is managed by the CLR. In other words, managed code is written to target the CLR. All code written in Visual Basic and C# is managed by default. Unmanaged code, on the other hand, does not benefit from the features provided by the CLR, such as garbage collection and type safety. 8. Is it possible to monitor the activities and performance of the CLR?

Ans: Yes. You can use Perfmon.exe in Windows 2000 to monitor the activities and performance of the CLR. Expand the Performance Logs and Alerts node. Double-click System Overview. In the System Overview Properties dialog box, click the Add button. In the Select Counters dialog box, select the Performance object drop-down list. This list displays various objects, such as .NET CLR Interop and .NET CLR Memory. You can add these objects and monitor the activities and performance of the CLR.

Solutions: Just a Minute


1. What are the various components of the .NET Framework?

Ans: The .NET Framework consists of Web Forms, Windows Forms, and Console applications that pertain to the presentation layer of an application. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the Common Language Runtime (CLR). 2. What is an assembly?

Ans: An assembly is a single deployable unit that contains all the information about the implementation of classes, structures, and interfaces. An assembly stores all the information about itself. This information is called metadata, and it includes the name and version number of the assembly, security information, information about the dependencies, and a list of the files that constitute an assembly.

Lesson Two
Experiences
Start the session by discussing different types of user interfaces. Specify that unlike in Visual Basic 6, you can create console applications in Visual Basic .NET. These applications are CUI-based. You can also create GUI-based applications in Visual Basic .NET by using Windows Forms and controls. Explain what are Windows Forms. Explain their properties, events, and methods. After explaining Windows Forms, state that Windows Forms and controls do not provide much functionality by themselves. You need to write code to provide functionality. While writing code, you need to use some programming language features such as data types, variables, and looping constructs. Discuss each of the programming constructs. Compare these constructs with the ones used in other programming languages such as C++ and Java. While discussing the demo, discuss some of the commonly used controls and their properties, methods, and events. Demonstrate the creation of controls by dragging them from the Toolbox and dropping them on the form. Use examples to demonstrate the use of controls and their events.

10 Programming in Visual Basic .NET-Coordinator Guide

NIIT

Execution support: The CLR provides the infrastructure that enables execution to take place as well
as a variety of services that can be used during execution.

Analogies and Examples


Depending on the profile of students, you may compare the process of compilation and execution of a .NET application with that of a Java application. In case of Java, when you compile the application code, bytecode is generated. The bytecode generated during compilation is platform independent. When you execute the application, the bytecode is interpreted and the application gets executed. In case of a .NET application, when you compile the application code, it is converted into Intermediate Language (IL), which is CPU-independent. This means that the code can be executed from any platform that supports the .NET CLR. However, unlike bytecode, IL is not interpreted. Instead, the JIT compiler translates the IL code into native code.

FAQs
1. What is the .NET Framework?

Ans: The .NET Framework is an environment for developing, deploying, and executing Windows and Web-based applications. It exists as a layer between .NET applications and the underlying operating system. In other words, the .NET Framework encapsulates much of the basic functionality that was earlier built into various programming languages, such as garbage collection, debugging, and security services. 2. What is the Common Language Runtime (CLR)?

Ans: The Common Language Runtime is the execution engine for .NET Framework applications. It performs a number of functions, such as loading and executing an application, performing automatic memory management, ensuring type safety, and handling exceptions. It is one of the most important components of the .NET Framework. 3. What is the Common Type System (CTS)?

Ans: The Common Type System is a type system built into the CLR. The CTS supports the data types found in most programming languages. 4. What is the Common Language Specification (CLS)?

Ans: The Common Language Specification is a subset of the CTS. It provides guidelines for library developers and compiler writers. It allows developers to create libraries that can be used in any language that supports the CLS. 5. What is MSIL?

Ans: Microsoft Intermediate Language is a CPU-independent instruction set. When you compile a .NET Framework application, it is converted into MSIL. When you execute the .NET Framework application on a computer, the instructions specified in MSIL are translated into the native code. MSIL ensure cross-language integration. Note that MSIL is not interpreted. 6. What is garbage collection?

Ans: Garbage collection is a process that detects objects that are no longer used by an application. It automatically releases the memory associated with the object. 7. What is the difference between managed code and unmanaged code?

NIIT

Programming in Visual Basic .NET-Coordinator Guide 9

After discussing Visual Basic .NET language features, state that you can use Visual Studio .NET to develop applications in Visual Basic .NET. Discuss all the components of the Visual Studio .NET IDE. State that Visual Studio .NET provides a common IDE across multiple languages, such as Visual C# and Visual Basic .NET. This is unlike Visual Studio 6.0, which provided a separate IDE for Visual Basic 6.0 and Visual InterDev. The common IDE enables the use of the same set of application development tools in different languages, thus simplifying the learning curve. Explain the concept of projects and solutions in Visual Studio .NET. Demonstrate how each component of the IDE can be used in application development. It is important for students to be familiar with all these components, as they will use the IDE in all the other lessons. If time permits, allow students to create their own projects and explore the features of the IDE.

Additional Inputs
Toolbox
The Toolbox contains various tabs. These tabs categorize controls, thereby making it easy to locate various controls. The following table describes various tabs:
Tab Data Description Displays objects that can be added to a Windows Form or a component. These objects allow you to connect to a database and retrieve and manipulate data. Displays the components that you can add to a Windows Form. It displays some predefined components, such as EventLog and MessageQueue. Displays a list of Windows Forms controls, such as a label, a text box, and a button. These controls are arranged based on their estimated frequency of use. Displays the text that is cut or copied in the Code Editor window. You can view the contents of the Clipboard Ring by clicking the Clipboard Ring tab of the Toolbox. The clipboard recalls the last 15 text items that were cut or copied. This is a powerful feature for quickly copying several pieces of text to a new location or for recalling text that you inadvertently cut. Used to store the default controls for a project. You can drag controls from other tabs to this tab. You can also add custom controls to this tab.

Components

Windows Forms

Clipboard Ring

General

Common Language Runtime


The .NET Framework provides a run-time environment called Common Language Runtime for managing the execution of code. Programming language compilers expose the functionality of the runtime and allow you to write code that benefits from the services provided by the runtime. Code developed with a language compiler that targets the CLR is known as managed code. The services provided by the CLR include:

Garbage collection: The CLR provides the garbage collection feature for managing the lifetime of
an object.

Common Type System (CTS): The CTS provides rules that language compilers follow with respect
to defining, referencing, using, and storing types.

Security: The CLR ensures that code can perform only those tasks for which it has permissions.
8 Programming in Visual Basic .NET-Coordinator Guide NIIT

L ESSON-SPECIFIC INPUTS
Lesson One
Experiences
Depending on the profile of students, you may start the session by discussing Windows Distributed interNet Architecture (DNA) and its limitations. Then, you can discuss how the new .NET initiative tries to solve these problems. A typical DNA-based application comprises three-tiers:

The presentation tier This tier deals with user interfaces for Windows and Web applications. The middle tier This tier encapsulates business logic. It handles interaction with the client on one
hand, and interacts with data repositories on the other. Components in this tier interact with a variety of protocols and other components to send data to the data tier.

The data tier This tier has components that store data. In addition it contains logic to process,
retrieve, and validate data. Today most software that run on Windows are based on the DNA model. However, there are several limitations of the DNA model. They are as follows:

Applications rely heavily on the COM components on the server and sometimes on the clients as
well. Developing COM components is a complex task in most languages. In addition, COM is difficult to deploy. For example, many a times, you might have applications that use the same COM component. However, while you are installing a new application, the newer version of the component might get installed. In such a case, the newly installed application may work well. However, the existing applications that depend on the older version of the component could stop functioning. This conflict is caused because the system does not keep track of the versions of different components used by different applications. In addition, the applications also do not specify information about the version of a component that it uses. This results in DLL conflicts.

Each programming language has its own set of data types. Same data type is defined differently in
different languages. Thus, passing parameters between applications that are written using different languages becomes a challenge.

The DNA model does not allow you to implement an integrated solution with both Windows- and
Web-based user interfaces. Microsofts .NET initiative aims at solving all these problems. For example, it introduces the concept of assemblies to keep track of the versions and dependencies between components. After discussing the DNA model and the .NET initiative, discuss the components of the .NET Framework. Explain the figure that depicts the .NET Framework components. Discuss the importance of the CLR and state that Visual Basic .NET is a programming language that targets the runtime. This implies that the compiler of any of these languages compiles the code to avail the services offered by the CLR. Discuss the features of the Visual Basic .NET language. Stress the fact that Visual Basic .NET is an object-oriented language. It supports all features of object-orientation, such as inheritance, polymorphism, abstraction, and encapsulation.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 7

ensure that an application does not access the address space of another application. In the .NET Framework, the CLR uses application domains to isolate applications. Thus, an application domain is a secure unit of processing in the .NET Framework. Microsoft .NET Remoting provides a framework to allow objects to interact with other objects residing in different application domains, different processes, and on different computers. .NET remoting provides services, such as channels, formatters, object activation and life cycle, and object registration to achieve interaction between remote objects. Channels are used as transport mediums when a client invokes a method of a remote object. A remote object may provide more than one channel. The client can select the channel that best suits its requirement. Formatters are used to encode and decode messages before the channel transports the messages. 9. Are there any certifications for Visual Basic .NET?

Ans: No. Currently there are no certifications for Visual Basic .NET. However, the concepts covered in this module map to the objectives of the Microsoft Visual Basic 6.0 Desktop exam.

6 Programming in Visual Basic .NET-Coordinator Guide

NIIT

FAQS
1. What is .NET? Ans: Microsoft's latest and ambitious initiative is commonly called .NET. Microsoft has introduced the .NET initiative with the intention of bridging the gap in interoperability between applications. It aims at integrating various programming languages and services. It is designed to make significant improvements in code reuse, code specialization, resource management, multi-language development, security, deployment, and administration. 2. What is the .NET Framework?

Ans: The .NET Framework is a new platform designed for easy application development. The .NET framework has two main components, the Common Language Runtime and the .NET class library. The Common Language Runtime manages the application code by supporting services, such as memory management and thread management. The .NET class library is a collection of reusable classes that can be used for developing applications. 3. On what platforms does the .NET Framework run?

Ans: The of the .NET Framework runs on Windows NT, Windows 2000, Windows 9x, and Windows ME. 4: Which programming languages are supported by the .NET Framework?

Ans: Any language can target the .NET Framework. Currently, you can build .NET programs in a number of languages, such as C++, Visual Basic .NET, JScript, and C#. Some third-party languages will also be available in the future for developing .NET Framework applications. These languages include COBOL, Eiffel, Perl, Python, and Smalltalk. 5. What is Visual Basic .NET?

Ans: Visual Basic .NET is the latest version of Visual Basic that allows easy creation of Web and n-tier applications. It supports features, such as Windows and Web Forms, ADO.NET for database connectivity, improved type safety, object-oriented features, and visual inheritance, that can help you create and deploy scalable Web sites. 6. Is Visual Basic .NET 100% compatible with Visual Basic 6.0?

Ans: Visual Basic .NET has been built from the ground up on the .NET platform to provide full access to the new platform. Now, the Visual Basic code can interoperate with the code written in other languages, such as Visual C#. For example, Visual Basic .NET has the same arrays and variable types as any other language that uses the Common Language Runtime. Some features, such as non-zero based arrays, GoSub, and DefInt have been removed from the language to make Visual Basic .NET the most productive tool for creating Windows-based applications and Web sites. 7. How can I upgrade a Visual Basic 6 application to Visual Basic .NET?

Ans: Visual Basic .NET allows you to upgrade from traditional Windows development by providing an upgradation wizard. The upgradation wizard is discussed in the Appendix of the Student Guide. 8. What is .NET Remoting?

Ans: Operating systems and run-time environments provide application isolation to ensure that the code in one application does not adversely affect another application. Isolating applications helps

NIIT

Programming in Visual Basic .NET-Coordinator Guide 5

EXIT PROFILE
At the end of this module, the student will be able to:

Create Windows Forms Use Visual Basic .NET programming language features to specify the application logic Create and instantiate a class Create an inherited form Use CommonDialog classes in an application Connect to a database by using ADO.NET components Access data from a database and bind it to a Windows Form Display filtered data in a Windows Form Update database records Create a Crystal Report to display summarized data Create menus Create MDI forms Perform File I/O operations Implement multi-threading operations in Visual Basic .NET Handle errors while accessing data Trace and debug errors in a Windows Form application Provide application assistance by creating Help Create reusable components and use them in an application Create and use user controls Create an ASP.NET Web service Use an ASP.NET Web service in Windows and Web-based applications Deploy a Windows application Deploy a component Deploy a Web service

4 Programming in Visual Basic .NET-Coordinator Guide

NIIT

ENTRY PROFILE
A student who registers for the Visual Basic .NET module should be able to perform the following tasks:

Knowledge of any OOP language Create tables and execute SQL queries Work in Windows environment Interact in English in a classroom environment

NIIT

Programming in Visual Basic .NET-Coordinator Guide 3

OBJECTIVES
This module will familiarize students with the following:

Using the Visual Studio .NET IDE to develop Visual Basic .NET applications Creating Windows Forms Using object-oriented programming features in Visual Basic .NET Creating procedures Using CommonDialog classes Retrieving and manipulating the data stored in a database by using ADO.NET Generating reports Creating MDI applications Creating menus Performing file I/O Creating multithreaded applications Handling exceptions Debugging applications Creating application assistance Creating and using components Creating user controls Creating and using Web services Deploying an application

2 Programming in Visual Basic .NET-Coordinator Guide

NIIT

RATIONALE
Why This Module
Most of the current applications meet the requirements of their users. However, they do not offer interoperability with other applications that run on different platforms. Microsoft has introduced the .NET initiative with the intension of bridging the gap in the interoperability between applications running on different platforms. .NET is Microsofts strategy for delivering software as a Web service. A Web service is a reusable component that can be accessed by a number of applications regardless of the platforms used to develop the applications. Visual Basic .NET is one of the programming languages that have been introduced as a part of the .NET initiative. Visual Basic .NET provides a number of programming language features that can be used to create powerful Windows- and Web-based applications. In this module, students will be introduced to the .NET initiative. They will learn about the .NET Framework and its components. Then, students will learn to use Visual Studio .NET to develop Visual Basic .NET applications. They will learn to use various features of Visual Basic .NET to create Windows applications and Web services.

NIIT

Programming in Visual Basic .NET-Coordinator Guide 1

Vous aimerez peut-être aussi