Unit 1: VB.Net Programming Working with Visual Basic

19
Unit 1: VB.Net Programming Bojamma K K, Dept. Of BCA, CCGPage 1 Chapter 1: Essential Visual Basic.Net VB.Net Programming Visual Basic(VB) is the most popular programming tool available today. Visual Basic itself, which has now become Visual Basic .NET (also called VB .NET) which supports windows application development now has integrated support for Web development too. Visual Basic Integrated Development Environment —the IDE—is used to develop all kinds of applications using VB language. The IDE is what you see when you start Visual Basic, and it's where you develop your applications and debug them. Working with Visual Basic The Visual Basic Integrated Development Environment is used to develop applications. In General ,there are three types of applications in Visual Basic—those based on Windows forms (such applications are usually local to your machine), Web forms (that come to you across the Internet), and console applications (that run in a DOS window). Creating a Windows Application To create an application based on Windows forms, select the New item in the File menu, then select the Project item in the submenu that appears. This brings up the New Project dialog box you see in Figure 1.2.

Transcript of Unit 1: VB.Net Programming Working with Visual Basic

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 1

Chapter 1:Essential Visual Basic.Net

VB.Net ProgrammingVisual Basic(VB) is the most popular programming tool available today. Visual Basic itself,which has now become Visual Basic .NET (also called VB .NET) which supports windowsapplication development now has integrated support for Web development too. Visual BasicIntegrated Development Environment —the IDE—is used to develop all kinds of applicationsusing VB language.The IDE is what you see when you start Visual Basic, and it's where you develop yourapplications and debug them.

Working with Visual BasicThe Visual Basic Integrated Development Environment is used to develop applications.

In General ,there are three types of applications in Visual Basic—those based on Windowsforms (such applications are usually local to your machine), Web forms (that come to youacross the Internet), and console applications (that run in a DOS window).

Creating a Windows ApplicationTo create an application based on Windows forms, select the New item in the File menu,then select the Project item in the submenu that appears. This brings up the New Projectdialog box you see in Figure 1.2.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 2

Select the folder labeled Visual Basic Projects in the Project Types box, and select theWindows Application project type in the Templates box. Name the new project—for example:WinHello—and specify where to store it—like c:\vbnet folder, as you see in Figure. Nowclick the OK button to create this new Visual Basic project. Visual Basic creates a newWindows project and gives you the result you see in Figure below.

The window you see at the center of Figure , labeled Form1, is the window that will becomeour new Windows application. In this case, three Windows controls are added to thisform—a text box,a label and a button. Controls are user-interface elements that you see inWindows all the time,which are present in toolbox and are dragged to the form whenrequired.Controls that appear in form can be customized using properties box. The Propertieswindow at the lower right of the IDE lists the properties of the currently selected control orobject.To execute an application, code has to be wriiten to each control which is done using codedesigner, for example code for button can be written as:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs)Handles Button1.Click

TextBox1.Text = "Hello from Visual Basic"End SubNow run the program by selecting the Debug|Start menu item, or by pressing F5.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 3

To close the application, click the X button at upper right, as you would with any Windowsapplication.

Creating a Web ApplicationTo create a new Web application in Visual Basic, you select the File|New|Project menu itemopening the New Project dialog box. Select the Visual Basic Projects folder in the ProjectTypes box, but this time, select ASP.NET Web Application in the Templates box. Give thisnew application the name.

To create a Web application, you need a Web server that uses the Microsoft InternetInformation Server (IIS) version 5.0 or later (with FrontPage extensions installed), and thatserver must be running. You can enter the location of your server in the Location box in theNew Projects dialog box; if you have IIS running on your local machine, Visual Basic will findit and use that server by default. When you click the OK button, Visual Basic will create thenew Web application.

Designing Web applications looks much like designing Windows applications. Web formunder design— called a page—is at the center of the IDE that says that we're using the Gridlayout mode. In this mode, controls will stay where you position them. The other layoutmode is the Flow layout mode; in this mode, the controls in your application will movearound, as they would in a standard Web page, depending on where the browser wants toput them.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 4

We can design our new Web application just as we did the Windows application— click theWeb forms item in the toolbox, and add both a text box and a button to the Web form andset the properties using properties window to the controls.

We can add the same code to handle the button click add this code:Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs)Handles Button1.Click

TextBox1.Text = "Hello from Visual Basic"End Sub

That's all it takes—now run the application by selecting the Debug|Start menu item, orpressing F5. The application comes up in your browser.

Creating a Console ApplicationThere's another new type of Visual Basic application in VB .NET—console applications.These applications are command-line based and run in DOS windows.To see how console applications work, use the File|New|Project menu item to open the NewProject menu item, and select Console Application in the Templates box. Name this newproject ConsoleHello. Then click OK to create the new project.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 5

When you create this new project, you see the result in Figure; note that in this case, becausethere is no user interface, Visual Basic opens the project directly to a code window.

Console applications are based on Visual Basic modules that are specifically designed tohold code that is not attached to any form or other such class. The code is written inside theprocedure and later you can run this program now by selecting the Debug|Start menu item;when the program runs, it displays both our message and the prompt about the Enter key, :

Module Module1Sub Main()

System.Console.WriteLine("Hello from Visual Basic")End Sub

End Module

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 6

What is the .Net Framework� Primarily a development platform (mostly effects application development)� Consists of three main parts

Common Language Runtime . Net Framework Class Library Languages

CLR (Common Language Runtime)� Provides a “runtime environment” for the execution of code written in ANY . Net

Language� The "Common Language Infrastructure" or CLI is a platform on which the . Net

programs are executed.� The CLI has the following key features:

Exception Handling - Exceptions are errors which occur when the application isexecuted.Garbage Collection - Garbage collection is the process of removing unwantedresources when they are no longer required.

� Working with Various programming languages –a developer can develop an application in a variety of .Net programming

languages.� Language - The first level is the programming language itself, the most common

ones are VB.Net and C#.� Compiler – There is a compiler which will be separate for each programming

language.� Common Language Interpreter – This is the final layer in .Net which would be used to

run a .net program developed in any programming language. So the subsequentcompiler will send the program to the CLI layer to run the .Net application.

.Net Framework Class Library� The .NET Framework includes a set of standard class libraries. A class library is a

collection of methods and functions that can be used for the core purpose.� For example, there is a class library with methods to handle all file-level operations.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 7

Most of the methods are split into either the System.* or Microsoft.* namespaces

System NamespacesA namespace is a logical separation of methods. You can't build a VB .NET applicationwithout using classes from the .NET System namespace. When you want to use a Windowsform, for example, you must use the System.Windows.Forms. Form class. A button in aWindows form comes from the System.Windows. Forms.Button class, and so on.An overview of some of those namespaces:

� System -Includes essential classes and base classes that definecommonlyused data types, events and event handlers, interfaces, attributes,exceptions, and so on.

� System.Collections -Includes interfaces and classes that define various collectionsof objects, including such collections as lists, queues, arrays, hash tables, anddictionaries.

� System.Data -Includes classes that make up ADO.NET. ADO.NET lets you builddata-handling components that manage data from multiple distributed data sources.

� System.Data.OleDb -Includes classes that support the OLE DB .NET data provider.� System.Data.SqlClient -Includes classes that support the SQL Server .NET

data provider.� System.Diagnostics -Includes classes that allow you to debug your application and

to step through your code. Also includes code to start system processes, read andwrite to event logs, and monitor system performance.

� System.Drawing -Provides access to the GDI+ graphics packages that give youaccess to drawing methods.

� System.Drawing.Drawing2D -Includes classes that support advancedtwodimensional and vector graphics.

� System.Drawing.Imaging -Includes classes that support advanced GDI+ imaging.� System.Drawing.Printing -Includes classes that allow you to customize and

perform printing.� System.Drawing.Text -Includes classes that support advanced GDI+ typography

operations. The classes in this namespace allow users to create and use collectionsof fonts.

� System.Globalization -Includes classes that specify culture-related information,including the language, the country/region, calendars, the format patterns for dates,currency and numbers, the sort order for strings, and so on.

� System.IO -Includes types that support synchronous and asynchronous readingfrom and writing to both data streams and files.

� System.Net -Provides an interface to many of the protocols used on the Internet.� System.Net.Sockets -Includes classes that support the Windows Sockets interface.

If you've worked with the Winsock API, you should be able to develop applicationsusing the Socket class.

� System.Reflection -Includes classes and interfaces that return information abouttypes, methods, and fields, and also have the ability to dynamically create and invoketypes.

� System.Security -Includes classes that support the structure of thecommon language runtime security system.

� System.Threading -Includes classes and interfaces that enable multithreadedprogramming.

� System.Web -Includes classes and interfaces that support browser/servercommunication.

� System.Web.Security -Includes classes that are used to implement ASP.NET securityin Web server applications.

� System.Web.Services -Includes classes that let you build and use Web services,

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 8

programmable entities on Web Server that code can communicate with usingstandard Internet protocols.

� System.Windows.Forms -Includes classes for creating Windows-based formsthat make use of the user interface controls and other features available in theWindows operating system.

� System.Xml -Includes classes that support processing of XML.

LanguagesThe types of applications that can be built in the .Net framework is classified broadly intothe following categories.

� WinForms – This is used for developing Forms-based applications, which would runon an end user machine. Notepad is an example of a client-based application.

� ASP.Net – This is used for developing web-based applications, which are made torun on any browser such as Internet Explorer, Chrome or Firefox.

� ADO.Net – This technology is used to develop applications to interact withDatabases such as Oracle or Microsoft SQL Server.

New Features in VB.Net

File Extensions Used in VB .NETWhen you save a solution, it's given the file extension .sln (such as WinHello.sln), and all theprojects in the solution are saved with the extension .vbproj. Here's a list of the types of fileextensions you'll see in files in VB .NET, and the kinds of files they correspond to; the mostpopular file extension is .vb..vb -Can be a basic Windows form, a code file, a module file for storing functions, a usercontrol, a data form, a custom control, an inherited form, a Web custom control, an inheriteduser control, a Windows service, a custom setup file, an image file for creating a customicon, or an AssemblyInfo file (used to store assembly information such as versioning andassembly name)..xsd -An XML schema provided to create typed datasets..xml -An XML document file..htm -An HTML document..tx t-A text file..xslt -An XSLT stylesheet file, used to transform XML documents and XML schemas..css -A cascading stylesheet file..rpt -A Crystal Report..bmp -A bitmap file..js -A JScript file (Microsoft's version of JavaScript)..vbs -A VBScript file..wsf -A Windows scripting file..aspx -A Web form..asp -An active server page..asmx -A Web service class..vsdisco -A dynamic discovery project; .vsdisco provides a means to enumerateall Web Services and all schemas in a Web project..web -A Web configuration file, .web configures Web settings for a Web project..asax -A global application class, used to handle global ASP.NET application-level events..resx -A resource file used to store resource information.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 9

New Featues in VB.Net� VB.Net can be used to develop all kinds of applications. aside from Windows

development, you can also create Web applications in VB .NET. In fact, there's a thirdalternative now—in addition to Windows applications and Web applications, you cancreate console applications, as you can in Java.

� . NET lets the user decide how the application to be used.� Visual Basic is completely object oriented now.� VB.NET provides new project templates for mobile based applications and Pocket PC

applications.� All OOP concepts are implemented in VB.Net.� VB.Net can create multi threaded applications. A threaded application

can do a number of different things at the same time, running different executionthreads. These threads can communicate with each other, pass data back and forth,and so on.

� VB .NET itself will usually tell you what you're doing wrong, and often will explain howto make it right. for example, you now have to declare all variables and objects,youmust always use parentheses when calling procedures, many keywords are eithergone or renamed, there are restrictions on declaring arrays, many old controls aregone and new ones have appeared, strict data typing is now enforced, and so on

Changes in Web DevelopmentThe big change in Web development is that you can do it at all. As you can see, however,Web development is now an integral part of VB .NET. The two major types of Webapplications are Web forms and Web services. Here's an overview:

� Web forms let you create Web-based applications with user interfaces. Theseapplications are based on ASP.NET (ASP stands for Active Server Pages,Microsoft'sWeb server technology). You can view these applications in any browser—theapplication will tailor itself to the browser's capabilities. You can build Webapplications that use standard HTML controls, or new Server controls, that arehandled on the Web server.

� Web services are made up of code that can be called by other components onthe Internet or applications that use Internet protocols. Web services may be used,for example, as the middle tier of distributed database applications on the Internet.You can also now check the data a user enters into a Web form using validationcontrols, which you can add to a Web form while designing it. You can bind thecontrols on a Web form to all kinds of different data sources, simply by draggingthose sources onto Web forms and setting a few properties.

Changes in Data HandlingThere have been many ways of handling data in previous versions of Visual Basic. Thingshave changed again; now you handle data with ADO.NET. ADO.NET is a new data-handlingmodel that makes it easy to handle data on the Internet. It's also what VB .NET uses on yourlocal machine to communicate with local databases. Here is an overview of what's new indata handling:

� Data is handled through ADO.NET, which facilitates development of Webapplications.

� ADO.NET is built on a disconnected data model that uses snapshots of data that areisolated from the data source. This means you can use and create disconnected,local datasets .

� Datasets are based on XML schema, so they can be strongly typed. There are manynew tools and a wizard for handling data in VB .NET, including tools to generatedatasets from data connections. You can use the connection wizard or the server

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 10

explorer to drag and drop whole tables from data sources, as well as creating dataadapters, connection objects, and more. You can now bind any control property todata from a data source. You can use the data classes provided in the .NETFramework to create and manipulate datasets in code.

Changes in the Visual Basic LanguageThere are many changes to the Visual Basic language itself. VB.NET now supports suchOOP features as inheritance, interfaces, and overloading that make it a strong OOPlanguage. You can now create multithreaded applications, and make use of structuredexception handling, custom attributes, and more. Here's an overview of some of thechanges to the language:

� It's all OOP now. All data items are objects now, based on the System.Objectclass. Even integers and other primitive data types are based on this class. And allcode has to be enclosed in a class.

� You can now create classes that serve as the base class for derived classes., this iscalled inheritance.

� You can now overload properties, methods, and procedures. Overloading means youcan define properties, methods, or procedures that have the same name but usedifferent data types.

� Visual Basic now supports structured exception handling, using an enhanced versionof the Try…Catch…Finally syntax supported by other languages (suchas C++).

� VB .NET now supports multithreaded applications.� VB .NET now supports constructors and destructors for use when initializing an

object of a specific class.� VB .NET is now strongly typed; this means you must declare all variables by default,

and you can't usually assign one data type to another. You use the� CType statement to convert between types. There are also changes in the way

you declare variables.User-defined types are no longer defined with the Type keyword, but rather with theStructure keyword.

� In Visual Basic 6.0, collections were part of the language itself; in VB .NET,they come from the Systems.Collections namespace, so we have to use the onesavailable in that namespace instead.

� There are a number of new compound arithmetic operators, such as +=, -=, •=,/=,\=,^=, and &=. These operators combine two operations in one, as in Java.

� The And, Or, Not, and Xor operators have changed from being bitwiseoperatorsto being Boolean operators, which only work on true/false values. The bitwiseversions are BitAnd, BitOr, BitNot, and BitXor.

� In VB6 most parameters were passed by reference; in Visual Basic .NET, thedefault is passing by value. The syntax for writing property procedures has changed(including the fact that

� Structured exception handling, including Try…Catch…Finally blocks, is nowsupported.

� In VB6, objects had a default property; for example, the default property of a TextBoxcontrol was the Text property; you could type TextBox1 = "Hello from Visual Basic"instead of TextBox1.Text = "Hello from Visual Basic".

� Event-handling procedures have changed; now event handlers are passed onlytwo parameters.

VB Integrated Development Environment

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 11

� An integrated development environment (IDE) is a software suite that consolidatesbasic tools required to write and test software.

� Development tools often include text editors, code libraries, compilers and testplatforms.

� An IDE typically contains a code editor, a compiler or interpreter, and a debugger,accessed through a single graphical user interface (GUI). The user writes andedits source code in the code editor. The compiler translates the source code into areadable language that is executable for a computer. And the debugger tests thesoftware to solve any issues or bugs.

� In the case of Visual Basic .NET, that IDE is Visual Studio.� Developed by Microsoft.

Components of VB IDE:1) The Start Page 2)The Menu System 2) Toolbars 3) The New Project Dialog Box 4)Graphical Designers 5)Code Designers 6) Intellisense 7)The Object Browser 8)TheToolbox 9) The Solution Explorer 10)The Class View Window 11) The Properties Window12)The Dynamic Help Window 13)Component Trays 14)The Server Explorer 15)TheOutput Window 16)The Task List 17)The Command Window

1. The Start PageThe Start page, which is what you see when you first start Visual Basic, You can usethe Start page to select from recent projects; by default, the Get Started item isselected in the Start page at upper left. You can also create a new project here byclicking the New Project button. The Start page has other useful aspects as well: forexample, because you use the same IDE for all Visual Studio languages, it'll alsosearch through all those languages when you search the help files.

2. The Menu SystemAfter you've started Visual Basic and have seen the Start page, you often turn to themenu system to proceed, as when you want to create a new project and use theFile|New|Project menu item to bring up the New Project dialog box. The IDE menusystem is very involved, with many items to choose from-and you don't even see it allat once. The menu system changes as you make selections in the rest of the IDE-forexample, the Project menu will display 16 items if you first select a project in theSolution Explorer, but only 4 items if you have selected a solution, not a project. Themenu system also allows you to switch from debug to release modes if you use theBuild|Configuration Manager item.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 12

3. ToolbarsThese appear near the top of the IDE. There are plenty of toolbars to choose from,and sometimes VB .NET will choose for you, as when it displays the Debug toolbarwhen you've launched a program with the Start item in the Debug menu. Because theIDE displays tool tips (those small yellow windows with explanatory text that appearwhen you let the mouse rest over controls such as buttons in a toolbar), it'seasy toget to know what the buttons in the toolbars do. Toolbars provide a quick way toselect menu items.

4. The New Project Dialog BoxWhen you want to create a new project, you turn to the New Project dialog box . Inaddition to letting you select from all the possible types of projects you can create inVisual Basic, you can also set the name of the project, and its location; for Windowsprojects, the location is a folder on disk.

5. Graphical DesignersWhen you're working on a project that has user interface elements-such as forms,VB.NET can display what those elements will look like at run time, and, of course,

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 13

that's what makes Visual Basic visual. For example, when you're looking at aWindows form, you're actually looking at a Windows form designer. There are severaldifferent types of graphical designers, including:Windows form designersWeb form designersComponent designersXML designers

6. Code DesignersUnlike graphical designers, code designers let you edit the code for a component,andyou can see a code designer in Figure. You can use the tabs at the top center of theIDE to switch between graphical designers .You can also switch between graphicaland code designers using the Designer and Code items in the View menu, or you canuse the top two buttons at left in the Solution Explorer. The two drop-down list boxesat the top of the code designer; the one on the leftlets you select what object's code you're working with, and the one on the right letsyou select the part of the code that you want to work on, letting you select betweenthedeclarations area, functions, Sub procedures, and methods

7. IntelliSenseOne useful feature of VB .NET code designers is Microsoft's IntelliSense. IntelliSenseiswhat's responsible for those boxes that open as you write your code, listing all thepossible options and even completing your typing for you. IntelliSense is made up of

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 14

a number of options, including:� List Members-Lists the members of an object.� Parameter Info-Lists the arguments of procedure calls.� Quick Info-Displays information in tool tips as the mouse rests on elements in

` your code.� Complete Word-Completes typed words.� Automatic Brace Matching-Adds parentheses or braces as needed.

8. The Object ExplorerThis tool lets you look at all the members of an object at once, The Object Explorerhelps open up any mysterious objects that Visual Basic has added to your code soyou can see what's going on inside. To open the Object Explorer, select View|OtherWindows|Object Explorer. The Object Explorer shows all the objects in your programand gives you access towhat's going on in all of them. To close the Object Explorer, just click the X button atits upper right.

9. The ToolboxThe toolbox uses tabs to divide its contents into categories; you can see these tabs,marked Data, Components, Windows Forms, and General. The Data, Components,Windows Forms, and General tabs appear when you're working with a Windows formin a Windows form designer. When you're working on a Web form, you'll see Data,Web Forms, Components, Components,HTML, Clipboard Ring, and General, and soon. The Data tab displays tools for creating datasets and making data connections,the Windows Forms tab displays tools for adding controls to Windows forms, theWeb Forms tab displays tools for adding server controls to Web forms, and so on.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 15

10. The Solution ExplorerThe Solution Explorer tracks the items in your projects; to add new items, you canuse the menu items in the Project menu, such as Add Windows Form and Add UserControl.To add new empty modules and classes to a project, you can use theProject|Add New Items menu item. The Solution Explorer sees things in terms offiles. There, the References folder holds the currently referenced items (such asnamespaces) in aproject, AssemblyInfo.vb is the file that holds information about theassembly you're creating, and Form1.vb is the file that holds the code for the formunder design.

11. The Class View WindowIf you click the Class View tab under the Solution Explorer, you'll see the ClassViewwindow, This view presents solutions and projects in terms ofthe classes theycontain, and the members of these classes. Using the Class View window gives youan easy way of jumping to a member of classthat you want to access quickly-justfind it in the Class View window, and double-click itto bring it up in a code designer.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 16

12. The Properties WindowThe Properties window is divided into two columns of text, with the properties ontheleft, and their settings on the right. The object you're setting properties forappears inthe drop-down list box at the top of the Properties window, and you canselect from all the available objects using that list box. When you select a property,Visual Basic will give you an explanation of the property in the panel at the bottom ofthe Properties window, as you see in Figure 1.30. And you can display the propertiesalphabetically by clicking the second button from the left at the top of the Propertieswindow, or in categories by clicking the left-most button. To change a property'ssetting, you only have to click the right-hand column next to the name of the property,and enter the new setting.

13. The Dynamic Help WindowThe window that shares the Properties window's space, however, is quite new-theDynamic Help window. Visual Basic .NET includes the usual Help menu withContents,Index, and Search items, of course, but it also now supports dynamic help, whichlooksthings up for you automatically.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 17

14. Component TraysWhen you add components that are invisible at run time they'll appear in acomponent tray, which will appear automatically in the designer.

15. The Server ExplorerYou use the Server Explorer, which appears in Figure 1.33, to explore what's going onina server, and it's a great tool to help make distant severs feel less distant, becauseyoucan see everything you need in an easy graphical environment. You can drag anddrop whole items onto Windows forms or Web forms from the Server Explorer.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 18

16. The Output WindowThe Output window, which you see in Figure gives you the results of building andrunning programs.

17. The Task ListThe Task List is another useful window. To see it, select the View|Show Tasks|All .Asits name implies, the Task List displays tasks that VB .NET assumes you still have totake care of, and when you click a task, the corresponding location in a code designerappears.

18. The Command WindowTo open command window, click on View|Other Windows|Command Window . youcan enter commands like File.AddNewProject here and VB .NET will display the AddNew Projectdialog box.

Unit 1: VB.Net Programming

Bojamma K K, Dept. Of BCA, CCGPage 19