VB.Net – Web Programming

VB.Net – Web Programming ”; Previous Next A dynamic web application consists of either or both of the following two types of programs − Server-side scripting − these are programs executed on a web server, written using server-side scripting languages like ASP (Active Server Pages) or JSP (Java Server Pages). Client-side scripting − these are programs executed on the browser, written using scripting languages like JavaScript, VBScript, etc. ASP.Net is the .Net version of ASP, introduced by Microsoft, for creating dynamic web pages by using server-side scripts. ASP.Net applications are compiled codes written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework. The ASP.Net application codes could be written in either of the following languages − Visual Basic .Net C# Jscript J# In this chapter, we will give a very brief introduction to writing ASP.Net applications using VB.Net. For detailed discussion, please consult the ASP.Net Tutorial. ASP.Net Built-in Objects ASP.Net has some built-in objects that run on a web server. These objects have methods, properties and collections that are used in application development. The following table lists the ASP.Net built-in objects with a brief description − Sr.No. Object & Description 1 Application Describes the methods, properties, and collections of the object that stores information related to the entire Web application, including variables and objects that exist for the lifetime of the application. You use this object to store and retrieve information to be shared among all users of an application. For example, you can use an Application object to create an e-commerce page. 2 Request Describes the methods, properties, and collections of the object that stores information related to the HTTP request. This includes forms, cookies, server variables, and certificate data. You use this object to access the information sent in a request from a browser to the server. For example, you can use a Request object to access information entered by a user in an HTML form. 3 Response Describes the methods, properties, and collections of the object that stores information related to the server”s response. This includes displaying content, manipulating headers, setting locales, and redirecting requests. You use this object to send information to the browser. For example, you use a Response object to send output from your scripts to a browser. 4 Server Describes the methods and properties of the object that provides methods for various server tasks. With these methods you can execute code, get error conditions, encode text strings, create objects for use by the Web page, and map physical paths. You use this object to access various utility functions on the server. For example, you may use the Server object to set a time out for a script. 5 Session Describes the methods, properties, and collections of the object that stores information related to the user”s session, including variables and objects that exist for the lifetime of the session. You use this object to store and retrieve information about particular user sessions. For example, you can use Session object to keep information about the user and his preference and keep track of pending operations. ASP.Net Programming Model ASP.Net provides two types of programming models − Web Forms − this enables you to create the user interface and the application logic that would be applied to various components of the user interface. WCF Services − this enables you to remote access some server-side functionalities. For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost same as you have already used for creating the Windows Applications. Web Forms Web forms consists of − User interface Application logic User interface consists of static HTML or XML elements and ASP.Net server controls. When you create a web application, HTML or XML elements and server controls are stored in a file with .aspx extension. This file is also called the page file. The application logic consists of code applied to the user interface elements in the page. You write this code in any of .Net language like, VB.Net, or C#. The following figure shows a Web Form in Design view − Example Let us create a new web site with a web form, which will show the current date and time, when a user clicks a button. Take the following steps − Select File → New → Web Site. The New Web Site Dialog Box appears. Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a location for saving the files. You need to add a Default page to the site. Right click the web site name in the Solution Explorer and select Add New Item option from the context menu. The Add New Item dialog box is displayed − Select Web Form option and provide a name for the default page. We have kept it as Default.aspx. Click the Add button. The Default page is shown in Source view Set the title for the Default web page by adding a value to the <Title> tag of the page, in the Source view − To add controls on the web page, go to the design view. Add three labels, a text box and a button on the form. Double-click the button and add the following code to the Click event of the button − Protected Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Label2.Visible = True Label2.Text = “Welcome to Tutorials Point: ” + TextBox1.Text Label3.Text = “You visited us at: ” + DateTime.Now.ToString() End Sub When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, the following page opens in the browser − Enter your name and click on the Submit button − Web Services A web service is a web application, which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture

VB.Net – Useful Resources

VB.Net – Useful Resources ”; Previous Next The following resources contain additional information on VB.Net. Please use them to get more in-depth knowledge on this topic. Useful Video Courses AutoCAD Programming Using VB.NET 104 Lectures 12 hours Arnold Higuit More Detail Programming AutoCAD to Excel using VB.NET – Hands On Training! 98 Lectures 9 hours Arnold Higuit More Detail Amazing things You Can do with VB.net Programming Language 18 Lectures 2 hours Ayman Elsaid Abdelwahed Khoshouey More Detail Learn How to Use Microsoft Office PowerPoint and Paint to Design Modern Forms for Visual Studio Featured 5 Lectures 1 hours Ayman Elsaid Abdelwahed Khoshouey More Detail Print Page Previous Next Advertisements ”;

VB.Net – Database Access

VB.Net – Database Access ”; Previous Next Applications communicate with a database, firstly, to retrieve the data stored there and present it in a user-friendly way, and secondly, to update the database by inserting, modifying and deleting data. Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is used by the .Net applications for retrieving, accessing and updating data. ADO.Net Object Model ADO.Net object model is nothing but the structured process flow through various components. The object model can be pictorially described as − The data residing in a data store or database is retrieved through the data provider. Various components of the data provider retrieve data for the application and update data. An application accesses data either through a dataset or a data reader. Datasets store data in a disconnected cache and the application retrieves data from it. Data readers provide data to the application in a read-only and forward-only mode. Data Provider A data provider is used for connecting to a database, executing commands and retrieving data, storing it in a dataset, reading the retrieved data and updating the database. The data provider in ADO.Net consists of the following four objects − Sr.No. Objects & Description 1 Connection This component is used to set up a connection with a data source. 2 Command A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source. 3 DataReader Data reader is used to retrieve data from a data source in a read-only and forward-only mode. 4 DataAdapter This is integral to the working of ADO.Net since data is transferred to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter. There are following different types of data providers included in ADO.Net The .Net Framework data provider for SQL Server – provides access to Microsoft SQL Server. The .Net Framework data provider for OLE DB – provides access to data sources exposed by using OLE DB. The .Net Framework data provider for ODBC – provides access to data sources exposed by ODBC. The .Net Framework data provider for Oracle – provides access to Oracle data source. The EntityClient provider – enables accessing data through Entity Data Model (EDM) applications. DataSet DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are retrieved from a database. When a connection is established with the database, the data adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the database is closed. This is called the ”disconnected architecture”. The dataset works as a virtual database containing tables, rows, and columns. The following diagram shows the dataset object model − The DataSet class is present in the System.Data namespace. The following table describes all the components of DataSet − Sr.No. Components & Description 1 DataTableCollection It contains all the tables retrieved from the data source. 2 DataRelationCollection It contains relationships and the links between tables in a data set. 3 ExtendedProperties It contains additional information, like the SQL statement for retrieving data, time of retrieval, etc. 4 DataTable It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and DataColumn objects. The DataTable objects are case-sensitive. 5 DataRelation It represents a relationship in the DataRelationshipCollection of the dataset. It is used to relate two DataTable objects to each other through the DataColumn objects. 6 DataRowCollection It contains all the rows in a DataTable. 7 DataView It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and navigation. 8 PrimaryKey It represents the column that uniquely identifies a row in a DataTable. 9 DataRow It represents a row in the DataTable. The DataRow object and its properties and methods are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The NewRow method is used to create a new row and the Add method adds a row to the table. 10 DataColumnCollection It represents all the columns in a DataTable. 11 DataColumn It consists of the number of columns that comprise a DataTable. Connecting to a Database The .Net Framework provides two types of Connection classes − SqlConnection − designed for connecting to Microsoft SQL Server. OleDbConnection − designed for connecting to a wide range of databases, like Microsoft Access and Oracle. Example 1 We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please consult ”SQL Server” tutorial for creating databases and database tables in SQL Server. Let us connect to this database. Take the following steps − Select TOOLS → Connect to Database Select a server name and the database name in the Add Connection dialog box. M Click on the Test Connection button to check if the connection succeeded. Add a DataGridView on the form. Click on the Choose Data Source combo box. Click on the Add Project Data Source link. This opens the Data Source Configuration Wizard. Select Database as the data source type Choose DataSet as the database model. Choose the connection already set up. Save the connection string. Choose the database object, Customers table in our example, and click the Finish button. Select the Preview Data link to see the data in the Results grid − When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − Example 2 In this example, let us access data in a DataGridView control using code. Take the following steps − Add a DataGridView control and a button in the form. Change the text of the button control to ”Fill”. Double click the button control to add the required code for the Click event of the

VB.Net – Exception Handling

VB.Net – Exception Handling ”; Previous Next An exception is a problem that arises during the execution of a program. An exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. VB.Net exception handling is built upon four keywords – Try, Catch, Finally and Throw. Try − A Try block identifies a block of code for which particular exceptions will be activated. It”s followed by one or more Catch blocks. Catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception. Finally − The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. Throw − A program throws an exception when a problem shows up. This is done using a Throw keyword. Syntax Assuming a block will raise an exception, a method catches an exception using a combination of the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the following − Try [ tryStatements ] [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] [ Exit Try ] ] [ Catch … ] [ Finally [ finallyStatements ] ] End Try You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Exception Classes in .Net Framework In the .Net Framework, exceptions are represented by classes. The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception. The following table provides some of the predefined exception classes derived from the Sytem.SystemException class − Exception Class Description System.IO.IOException Handles I/O errors. System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type. System.NullReferenceException Handles errors generated from deferencing a null object. System.DivideByZeroException Handles errors generated from dividing a dividend with zero. System.InvalidCastException Handles errors generated during typecasting. System.OutOfMemoryException Handles errors generated from insufficient free memory. System.StackOverflowException Handles errors generated from stack overflow. Handling Exceptions VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the Try, Catch and Finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs − Live Demo Module exceptionProg Sub division(ByVal num1 As Integer, ByVal num2 As Integer) Dim result As Integer Try result = num1 num2 Catch e As DivideByZeroException Console.WriteLine(“Exception caught: {0}”, e) Finally Console.WriteLine(“Result: {0}”, result) End Try End Sub Sub Main() division(25, 0) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Exception caught: System.DivideByZeroException: Attempted to divide by zero. at … Result: 0 Creating User-Defined Exceptions You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this − Live Demo Module exceptionProg Public Class TempIsZeroException : Inherits ApplicationException Public Sub New(ByVal message As String) MyBase.New(message) End Sub End Class Public Class Temperature Dim temperature As Integer = 0 Sub showTemp() If (temperature = 0) Then Throw (New TempIsZeroException(“Zero Temperature found”)) Else Console.WriteLine(“Temperature: {0}”, temperature) End If End Sub End Class Sub Main() Dim temp As Temperature = New Temperature() Try temp.showTemp() Catch e As TempIsZeroException Console.WriteLine(“TempIsZeroException: {0}”, e.Message) End Try Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − TempIsZeroException: Zero Temperature found Throwing Objects You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as − Throw [ expression ] The following program demonstrates this − Module exceptionProg Sub Main() Try Throw New ApplicationException(“A custom exception _ is being thrown here…”) Catch e As Exception Console.WriteLine(e.Message) Finally Console.WriteLine(“Now inside the Finally Block”) End Try Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − A custom exception is being thrown here… Now inside the Finally Block Print Page Previous Next Advertisements ”;

VB.Net – Decision Making

VB.Net – Decision Making ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − VB.Net provides the following types of decision making statements. Click the following links to check their details. Statement Description If … Then statement An If…Then statement consists of a boolean expression followed by one or more statements. If…Then…Else statement An If…Then statement can be followed by an optional Else statement, which executes when the boolean expression is false. nested If statements You can use one If or Else if statement inside another If or Else if statement(s). Select Case statement A Select Case statement allows a variable to be tested for equality against a list of values. nested Select Case statements You can use one select case statement inside another select case statement(s). Print Page Previous Next Advertisements ”;

VB.Net – File Handling

VB.Net – File Handling ”; Previous Next A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). VB.Net I/O Classes The System.IO namespace has various classes that are used for performing various operations with files, like creating and deleting files, reading from or writing to a file, closing a file, etc. The following table shows some commonly used non-abstract classes in the System.IO namespace − I/O Class Description BinaryReader Reads primitive data from a binary stream. BinaryWriter Writes primitive data in binary format. BufferedStream A temporary storage for a stream of bytes. Directory Helps in manipulating a directory structure. DirectoryInfo Used for performing operations on directories. DriveInfo Provides information for the drives. File Helps in manipulating files. FileInfo Used for performing operations on files. FileStream Used to read from and write to any location in a file. MemoryStream Used for random access of streamed data stored in memory. Path Performs operations on path information. StreamReader Used for reading characters from a byte stream. StreamWriter Is used for writing characters to a stream. StringReader Is used for reading from a string buffer. StringWriter Is used for writing into a string buffer. The FileStream Class The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows − Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>) For example, for creating a FileStream object F for reading a file named sample.txt − Dim f1 As FileStream = New FileStream(“sample.txt”, FileMode.OpenOrCreate, FileAccess.ReadWrite) Parameter Description FileMode The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are − Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Create − It creates a new file. CreateNew − It specifies to the operating system that it should create a new file. Open − It opens an existing file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate − It opens an existing file and truncates its size to zero bytes. FileAccess FileAccess enumerators have members: Read, ReadWrite and Write. FileShare FileShare enumerators have the following members − Inheritable − It allows a file handle to pass inheritance to the child processes None − It declines sharing of the current file Read − It allows opening the file for reading ReadWrite − It allows opening the file for reading and writing Write − It allows opening the file for writing Example The following program demonstrates use of the FileStream class − Live Demo Imports System.IO Module fileProg Sub Main() Dim f1 As FileStream = New FileStream(“sample.txt”, _ FileMode.OpenOrCreate, FileAccess.ReadWrite) Dim i As Integer For i = 0 To 20 f1.WriteByte(CByte(i)) Next i f1.Position = 0 For i = 0 To 20 Console.Write(“{0} “, f1.ReadByte()) Next i f1.Close() Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1 Advanced File Operations in VB.Net The preceding example provides simple file operations in VB.Net. However, to utilize the immense powers of System.IO classes, you need to know the commonly used properties and methods of these classes. We will discuss these classes and the operations they perform in the following sections. Please click the links provided to get to the individual sections − Sr.No. Topic and Description 1 Reading from and Writing into Text files It involves reading from and writing into text files. The StreamReader and StreamWriter classes help to accomplish it. 2 Reading from and Writing into Binary files It involves reading from and writing into binary files. The BinaryReader and BinaryWriter classes help to accomplish this. 3 Manipulating the Windows file system It gives a VB.Net programmer the ability to browse and locate Windows files and directories. Print Page Previous Next Advertisements ”;

VB.Net – Event Handling

VB.Net – Event Handling ”; Previous Next Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system generated notifications. Applications need to respond to events when they occur. Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of events. An event is an action that calls a function or may cause another event. Event handlers are functions that tell how to respond to an event. VB.Net is an event-driven language. There are mainly two types of events − Mouse events Keyboard events Handling Mouse Events Mouse events occur with mouse movements in forms and controls. Following are the various mouse events related with a Control class − MouseDown − it occurs when a mouse button is pressed MouseEnter − it occurs when the mouse pointer enters the control MouseHover − it occurs when the mouse pointer hovers over the control MouseLeave − it occurs when the mouse pointer leaves the control MouseMove − it occurs when the mouse pointer moves over the control MouseUp − it occurs when the mouse pointer is over the control and the mouse button is released MouseWheel − it occurs when the mouse wheel moves and the control has focus The event handlers of the mouse events get an argument of type MouseEventArgs. The MouseEventArgs object is used for handling mouse events. It has the following properties − Buttons − indicates the mouse button pressed Clicks − indicates the number of clicks Delta − indicates the number of detents the mouse wheel rotated X − indicates the x-coordinate of mouse click Y − indicates the y-coordinate of mouse click Example Following is an example, which shows how to handle mouse events. Take the following steps − Add three labels, three text boxes and a button control in the form. Change the text properties of the labels to – Customer ID, Name and Address, respectively. Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively. Change the text property of the button to ”Submit”. Add the following code in the code editor window − Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ” Set the caption bar text of the form. Me.Text = “tutorialspont.com” End Sub Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_ Handles txtID.MouseEnter ”code for handling mouse enter on ID textbox txtID.BackColor = Color.CornflowerBlue txtID.ForeColor = Color.White End Sub Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _ Handles txtID.MouseLeave ”code for handling mouse leave on ID textbox txtID.BackColor = Color.White txtID.ForeColor = Color.Blue End Sub Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _ Handles txtName.MouseEnter ”code for handling mouse enter on Name textbox txtName.BackColor = Color.CornflowerBlue txtName.ForeColor = Color.White End Sub Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _ Handles txtName.MouseLeave ”code for handling mouse leave on Name textbox txtName.BackColor = Color.White txtName.ForeColor = Color.Blue End Sub Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _ Handles txtAddress.MouseEnter ”code for handling mouse enter on Address textbox txtAddress.BackColor = Color.CornflowerBlue txtAddress.ForeColor = Color.White End Sub Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _ Handles txtAddress.MouseLeave ”code for handling mouse leave on Address textbox txtAddress.BackColor = Color.White txtAddress.ForeColor = Color.Blue End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click MsgBox(“Thank you ” & txtName.Text & “, for your kind cooperation”) End Sub End Class When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − Try to enter text in the text boxes and check the mouse events − Handling Keyboard Events Following are the various keyboard events related with a Control class − KeyDown − occurs when a key is pressed down and the control has focus KeyPress − occurs when a key is pressed and the control has focus KeyUp − occurs when a key is released while the control has focus The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This object has the following properties − Alt − it indicates whether the ALT key is pressed Control − it indicates whether the CTRL key is pressed Handled − it indicates whether the event is handled KeyCode − stores the keyboard code for the event KeyData − stores the keyboard data for the event KeyValue − stores the keyboard value for the event Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed Shift − it indicates if the Shift key is pressed The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This object has the following properties − Handled − indicates if the KeyPress event is handled KeyChar − stores the character corresponding to the key pressed Example Let us continue with the previous example to show how to handle keyboard events. The code will verify that the user enters some numbers for his customer ID and age. Add a label with text Property as ”Age” and add a corresponding text box named txtAge. Add the following codes for handling the KeyUP events of the text box txtID. Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _ Handles txtID.KeyUp If (Not Char.IsNumber(ChrW(e.KeyCode))) Then MessageBox.Show(“Enter numbers for your Customer ID”) txtID.Text = ” ” End If End Sub Add the following codes for handling the KeyUP events of the text box txtID. Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _ Handles txtAge.KeyUp If (Not Char.IsNumber(ChrW(e.keyCode))) Then MessageBox.Show(“Enter numbers for age”) txtAge.Text = ” ” End If End Sub When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning message box and clears the respective

VB.Net – Subs

VB.Net – Sub Procedures ”; Previous Next As we mentioned in the previous chapter, Sub procedures are procedures that do not return any value. We have been using the Sub procedure Main in all our examples. We have been writing console applications so far in these tutorials. When these applications start, the control goes to the Main Sub procedure, and it in turn, runs any other statements constituting the body of the program. Defining Sub Procedures The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for the Sub statement is − [Modifiers] Sub SubName [(ParameterList)] [Statements] End Sub Where, Modifiers − specify the access level of the procedure; possible values are – Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing. SubName − indicates the name of the Sub ParameterList − specifies the list of the parameters Example The following example demonstrates a Sub procedure CalculatePay that takes two parameters hours and wages and displays the total pay of an employee − Live Demo Module mysub Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal) ”local variable declaration Dim pay As Double pay = hours * wage Console.WriteLine(“Total Pay: {0:C}”, pay) End Sub Sub Main() ”calling the CalculatePay Sub Procedure CalculatePay(25, 10) CalculatePay(40, 20) CalculatePay(30, 27.5) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Total Pay: $250.00 Total Pay: $800.00 Total Pay: $825.00 Passing Parameters by Value This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter inside the method have no effect on the argument. In VB.Net, you declare the reference parameters using the ByVal keyword. The following example demonstrates the concept − Live Demo Module paramByval Sub swap(ByVal x As Integer, ByVal y As Integer) Dim temp As Integer temp = x ” save the value of x x = y ” put y into x y = temp ”put temp into y End Sub Sub Main() ” local variable definition Dim a As Integer = 100 Dim b As Integer = 200 Console.WriteLine(“Before swap, value of a : {0}”, a) Console.WriteLine(“Before swap, value of b : {0}”, b) ” calling a function to swap the values ” swap(a, b) Console.WriteLine(“After swap, value of a : {0}”, a) Console.WriteLine(“After swap, value of b : {0}”, b) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200 It shows that there is no change in the values though they had been changed inside the function. Passing Parameters by Reference A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. In VB.Net, you declare the reference parameters using the ByRef keyword. The following example demonstrates this − Live Demo Module paramByref Sub swap(ByRef x As Integer, ByRef y As Integer) Dim temp As Integer temp = x ” save the value of x x = y ” put y into x y = temp ”put temp into y End Sub Sub Main() ” local variable definition Dim a As Integer = 100 Dim b As Integer = 200 Console.WriteLine(“Before swap, value of a : {0}”, a) Console.WriteLine(“Before swap, value of b : {0}”, b) ” calling a function to swap the values ” swap(a, b) Console.WriteLine(“After swap, value of a : {0}”, a) Console.WriteLine(“After swap, value of b : {0}”, b) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100 Print Page Previous Next Advertisements ”;

VB.Net – Operators

VB.Net – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used operators − Arithmetic Operators Comparison Operators Logical/Bitwise Operators Bit Shift Operators Assignment Operators Miscellaneous Operators This tutorial will explain the most commonly used operators. Arithmetic Operators Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then − Show Examples Operator Description Example ^ Raises one operand to the power of another B^A will give 49 + Adds two operands A + B will give 9 – Subtracts second operand from the first A – B will give -5 * Multiplies both operands A * B will give 14 / Divides one operand by another and returns a floating point result B / A will give 3.5 Divides one operand by another and returns an integer result B A will give 3 MOD Modulus Operator and remainder of after an integer division B MOD A will give 1 Comparison Operators Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example = Checks if the values of two operands are equal or not; if yes, then condition becomes true. (A = B) is not true. <> Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true. (A <> B) is true. > Checks if the value of left operand is greater than the value of right operand; if yes, then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand; if yes, then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then condition becomes true. (A <= B) is true. Apart from the above, VB.Net provides three more comparison operators, which we will be using in forthcoming chapters; however, we give a brief description here. Is Operator − It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False. IsNot Operator − It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True. Like Operator − It compares a string against a pattern. Logical/Bitwise Operators Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False, then − Show Examples Operator Description Example And It is the logical as well as bitwise AND operator. If both the operands are true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions. (A And B) is False. Or It is the logical as well as bitwise OR operator. If any of the two operands is true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions. (A Or B) is True. Not It is the logical as well as bitwise NOT operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. Not(A And B) is True. Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns True if both expressions are True or both expressions are False; otherwise it returns False. This operator does not perform short-circuiting, it always evaluates both expressions and there is no short-circuiting counterpart of this operator. A Xor B is True. AndAlso It is the logical AND operator. It works only on Boolean data. It performs short-circuiting. (A AndAlso B) is False. OrElse It is the logical OR operator. It works only on Boolean data. It performs short-circuiting. (A OrElse B) is True. IsFalse It determines whether an expression is False. IsTrue It determines whether an expression is True. Bit Shift Operators We have already discussed the bitwise operators. The bit shift operators perform the shift operations on binary values. Before coming into the bit shift operators, let us understand the bit operations. Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A  = 1100 0011 We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit shift operators are >> and << for left shift and right shift, respectively. Assume that the variable A holds 60 and variable B holds 13, then − Show Examples Operator Description Example And Bitwise AND Operator copies a bit to the result if it exists in both operands. (A AND B) will give 12, which is 0000 1100 Or Binary OR Operator copies a bit if it exists in either operand. (A Or B) will give 61, which is 0011 1101 Xor Binary XOR Operator copies the bit if it is set

VB.Net – Directives

VB.Net – Directives ”; Previous Next The VB.Net compiler directives give instructions to the compiler to preprocess the information before actual compilation starts. All these directives begin with #, and only white-space characters may appear before a directive on a line. These directives are not statements. VB.Net compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In VB.Net, the compiler directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. Compiler Directives in VB.Net VB.Net provides the following set of compiler directives − The #Const Directive The #ExternalSource Directive The #If…Then…#Else Directives The #Region Directive The #Const Directive This directive defines conditional compiler constants. Syntax for this directive is − #Const constname = expression Where, constname − specifies the name of the constant. Required. expression − it is either a literal, or other conditional compiler constant, or a combination including any or all arithmetic or logical operators except Is. For example, #Const state = “WEST BENGAL” Example The following code demonstrates a hypothetical use of the directive − Live Demo Module mydirectives #Const age = True Sub Main() #If age Then Console.WriteLine(“You are welcome to the Robotics Club”) #End If Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − You are welcome to the Robotics Club The #ExternalSource Directive This directive is used for indicating a mapping between specific lines of source code and text external to the source. It is used only by the compiler and the debugger has no effect on code compilation. This directive allows including external code from an external code file into a source code file. Syntax for this directive is − #ExternalSource( StringLiteral , IntLiteral ) [ LogicalLine ] #End ExternalSource The parameters of #ExternalSource directive are the path of external file, line number of the first line, and the line where the error occurred. Example The following code demonstrates a hypothetical use of the directive − Module mydirectives Public Class ExternalSourceTester Sub TestExternalSource() #ExternalSource(“c:vbprogsdirectives.vb”, 5) Console.WriteLine(“This is External Code. “) #End ExternalSource End Sub End Class Sub Main() Dim t As New ExternalSourceTester() t.TestExternalSource() Console.WriteLine(“In Main.”) Console.ReadKey() End Sub When the above code is compiled and executed, it produces the following result − This is External Code. In Main. The #If…Then…#Else Directives This directive conditionally compiles selected blocks of Visual Basic code. Syntax for this directive is − #If expression Then statements [ #ElseIf expression Then [ statements ] … #ElseIf expression Then [ statements ] ] [ #Else [ statements ] ] #End If For example, #Const TargetOS = “Linux” #If TargetOS = “Windows 7″ Then ” Windows 7 specific code #ElseIf TargetOS = “WinXP” Then ” Windows XP specific code #Else ” Code for other OS #End if Example The following code demonstrates a hypothetical use of the directive − Live Demo Module mydirectives #Const classCode = 8 Sub Main() #If classCode = 7 Then Console.WriteLine(“Exam Questions for Class VII”) #ElseIf classCode = 8 Then Console.WriteLine(“Exam Questions for Class VIII”) #Else Console.WriteLine(“Exam Questions for Higher Classes”) #End If Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Exam Questions for Class VIII The #Region Directive This directive helps in collapsing and hiding sections of code in Visual Basic files. Syntax for this directive is − #Region “identifier_string” #End Region For example, #Region “StatsFunctions” ” Insert code for the Statistical functions here. #End Region Print Page Previous Next Advertisements ”;