VB.Net – Date & Time

VB.Net – Date & Time ”; Previous Next Most of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. VB.Net also provides powerful tools for date arithmetic that makes manipulating dates easy. The Date data type contains date values, time values, or date and time values. The default value of Date is 0:00:00 (midnight) on January 1, 0001. The equivalent .NET data type is System.DateTime. The DateTime structure represents an instant in time, typically expressed as a date and time of day ”Declaration <SerializableAttribute> _ Public Structure DateTime _ Implements IComparable, IFormattable, IConvertible, ISerializable, IComparable(Of DateTime), IEquatable(Of DateTime) You can also get the current date and time from the DateAndTime class. The DateAndTime module contains the procedures and properties used in date and time operations. ”Declaration <StandardModuleAttribute> _ Public NotInheritable Class DateAndTime Note: Both the DateTime structure and the DateAndTime module contain properties like Now and Today, so often beginners find it confusing. The DateAndTime class belongs to the Microsoft.VisualBasic namespace and the DateTime structure belongs to the System namespace. Therefore, using the later would help you in porting your code to another .Net language like C#. However, the DateAndTime class/module contains all the legacy date functions available in Visual Basic. Properties and Methods of the DateTime Structure The following table lists some of the commonly used properties of the DateTime Structure − Sr.No Property Description 1 Date Gets the date component of this instance. 2 Day Gets the day of the month represented by this instance. 3 DayOfWeek Gets the day of the week represented by this instance. 4 DayOfYear Gets the day of the year represented by this instance. 5 Hour Gets the hour component of the date represented by this instance. 6 Kind Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. 7 Millisecond Gets the milliseconds component of the date represented by this instance. 8 Minute Gets the minute component of the date represented by this instance. 9 Month Gets the month component of the date represented by this instance. 10 Now Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. 11 Second Gets the seconds component of the date represented by this instance. 12 Ticks Gets the number of ticks that represent the date and time of this instance. 13 TimeOfDay Gets the time of day for this instance. 14 Today Gets the current date. 15 UtcNow Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC). 16 Year Gets the year component of the date represented by this instance. The following table lists some of the commonly used methods of the DateTime structure − Sr.No Method Name & Description 1 Public Function Add (value As TimeSpan) As DateTime Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance. 2 Public Function AddDays ( value As Double) As DateTime Returns a new DateTime that adds the specified number of days to the value of this instance. 3 Public Function AddHours (value As Double) As DateTime Returns a new DateTime that adds the specified number of hours to the value of this instance. 4 Public Function AddMinutes (value As Double) As DateTime Returns a new DateTime that adds the specified number of minutes to the value of this instance. 5 Public Function AddMonths (months As Integer) As DateTime Returns a new DateTime that adds the specified number of months to the value of this instance. 6 Public Function AddSeconds (value As Double) As DateTime Returns a new DateTime that adds the specified number of seconds to the value of this instance. 7 Public Function AddYears (value As Integer ) As DateTime Returns a new DateTime that adds the specified number of years to the value of this instance. 8 Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. 9 Public Function CompareTo (value As DateTime) As Integer Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. 10 Public Function Equals (value As DateTime) As Boolean Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance. 11 Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean Returns a value indicating whether two DateTime instances have the same date and time value. 12 Public Overrides Function ToString As String Converts the value of the current DateTime object to its equivalent string representation. The above list of methods is not exhaustive, please visit Microsoft documentation for the complete list of methods and properties of the DateTime structure. Creating a DateTime Object You can create a DateTime object in one of the following ways − By calling a DateTime constructor from any of the overloaded DateTime constructors. By assigning the DateTime object a date and time value returned by a property or method. By parsing the string representation of a date and time value. By calling the DateTime structure”s implicit default constructor. The following example demonstrates this − Live Demo Module Module1 Sub Main() ”DateTime constructor: parameters year, month, day, hour, min, sec Dim date1 As New Date(2012, 12, 16, 12, 0, 0) ”initializes a new DateTime value Dim date2 As Date = #12/16/2012 12:00:52 AM# ”using properties Dim date3 As Date = Date.Now Dim date4 As Date = Date.UtcNow Dim date5 As Date = Date.Today Console.WriteLine(date1) Console.WriteLine(date2)

VB.Net – Data Types

VB.Net – Data Types ”; Previous Next Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. Data Types Available in VB.Net VB.Net provides a wide range of data types. The following table shows all the data types available − Data Type Storage Allocation Value Range Boolean Depends on implementing platform True or False Byte 1 byte 0 through 255 (unsigned) Char 2 bytes 0 through 65535 (unsigned) Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999 Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9…E+28) with no decimal point; 0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal Double 8 bytes -1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values 4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed) Long 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807(signed) Object 4 bytes on 32-bit platform 8 bytes on 64-bit platform Any type can be stored in a variable of type Object SByte 1 byte -128 through 127 (signed) Short 2 bytes -32,768 through 32,767 (signed) Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values String Depends on implementing platform 0 to approximately 2 billion Unicode characters UInteger 4 bytes 0 through 4,294,967,295 (unsigned) ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned) User-Defined Depends on implementing platform Each member of the structure has a range determined by its data type and independent of the ranges of the other members UShort 2 bytes 0 through 65,535 (unsigned) Example The following example demonstrates use of some of the types − Live Demo Module DataTypes Sub Main() Dim b As Byte Dim n As Integer Dim si As Single Dim d As Double Dim da As Date Dim c As Char Dim s As String Dim bl As Boolean b = 1 n = 1234567 si = 0.12345678901234566 d = 0.12345678901234566 da = Today c = “U”c s = “Me” If ScriptEngine = “VB” Then bl = True Else bl = False End If If bl Then ”the oath taking Console.Write(c & ” and,” & s & vbCrLf) Console.WriteLine(“declaring on the day of: {0}”, da) Console.WriteLine(“We will learn VB.Net seriously”) Console.WriteLine(“Lets see what happens to the floating point variables:”) Console.WriteLine(“The Single: {0}, The Double: {1}”, si, d) End If Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − U and, Me declaring on the day of: 12/4/2012 12:00:00 PM We will learn VB.Net seriously Lets see what happens to the floating point variables: The Single:0.1234568, The Double: 0.123456789012346 The Type Conversion Functions in VB.Net VB.Net provides the following in-line type conversion functions − Sr.No. Functions & Description 1 CBool(expression) Converts the expression to Boolean data type. 2 CByte(expression) Converts the expression to Byte data type. 3 CChar(expression) Converts the expression to Char data type. 4 CDate(expression) Converts the expression to Date data type 5 CDbl(expression) Converts the expression to Double data type. 6 CDec(expression) Converts the expression to Decimal data type. 7 CInt(expression) Converts the expression to Integer data type. 8 CLng(expression) Converts the expression to Long data type. 9 CObj(expression) Converts the expression to Object type. 10 CSByte(expression) Converts the expression to SByte data type. 11 CShort(expression) Converts the expression to Short data type. 12 CSng(expression) Converts the expression to Single data type. 13 CStr(expression) Converts the expression to String data type. 14 CUInt(expression) Converts the expression to UInt data type. 15 CULng(expression) Converts the expression to ULng data type. 16 CUShort(expression) Converts the expression to UShort data type. Example The following example demonstrates some of these functions − Live Demo Module DataTypes Sub Main() Dim n As Integer Dim da As Date Dim bl As Boolean = True n = 1234567 da = Today Console.WriteLine(bl) Console.WriteLine(CSByte(bl)) Console.WriteLine(CStr(bl)) Console.WriteLine(CStr(da)) Console.WriteLine(CChar(CChar(CStr(n)))) Console.WriteLine(CChar(CStr(da))) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − True -1 True 12/4/2012 1 1 Print Page Previous Next Advertisements ”;

VB.Net – Home

VB.Net Programming Tutorial Table of content VB.Net Tutorial Why to Learn VB.Net? VB.Net Applications Who Should Learn VB.Net Prerequisites to Learn VB.Net VB.Net Jobs and Opportunities Frequently Asked Questions about VB.Net PDF Version Quick Guide Resources Job Search Discussion VB.Net Tutorial VB.Net is a simple, modern, object-oriented computer programming language developed by Microsoft to combine the power of .NET Framework and the common language runtime with the productivity benefits that are the hallmark of Visual Basic. This tutorial will teach you basic VB.Net programming and will also take you through various advanced concepts related to VB.Net programming language. Why to Learn VB.Net? VB.Net was introduced in 2002 by Microsoft. It is an object-oriented language that can be used to develop software applications for Windows. So, if you are one who aspires to become a full stack developer, VB.Net must be your first programming language as it can be used to develop front-end as well as back-end of an application. In addition to this, following could be the reason for learning VB.Net − Object-Oriented Programming (OOP) Features − Learning VB.Net provides a solid foundation in OOP principles as it is an object-oriented language. These principles are applicable across various other programming languages like C++ and Java. OOP allows developers to write reusable code. Support from Microsoft − As this language was developed by Microsoft, it provides strong support and integration with the .NET framework. Therefore, developers get access to a vast library of pre-coded solutions and a robust development environment in Visual Studio. Community and Resources − There is a strong community of VB.Net developers who learn and build variety of applications. You could also be a part of that community after learning it. User-Friendly − VB.Net is designed to be user-friendly. Its syntax is very simple and straightforward. New programmers can quickly learn, adapt and start developing applications. VB.Net Applications After integrating with the .NET framework, the Visual Basic programming language has become one of the preferred choices for building a wide range of software and applications. Following are the areas where VB.NET is used − Mobile and Web Applications − ASP.NET which is a framework designed for building web applications, works with VB.Net. Also, with the release of a cross-platform development tool named Xamarin, VB.Net can be used for developing mobile applications. Gaming − This programming language can also be used in gaming industry. Although it is not as popular in the gaming industry as other languages like C#, VB.Net can develop smaller-scale games for the Windows platform. Standard Window Software − This is the area where VB.Net is most commonly used. Console Application − It is also a popular choice for developing console applications. These applications run using only a command line rather than a GUI. Who Should Learn VB.Net This tutorial has been prepared for the beginners to help them understand basic VB.Net programming. After completing this tutorial, you will find yourself at a moderate level of expertise in VB.Net programming from where you can take yourself to next levels. Prerequisites to Learn VB.Net VB.Net programming is very much based on BASIC and Visual Basic programming languages, so if you have basic understanding on these programming languages, then it will be a fun for you to learn VB.Net programming language. VB.Net Jobs and Opportunities Following are the great companies who keep recruiting .Net professionals like DotNet MVC Developer, Dot net developer, Web developer, .Net/VB Scripting Developer, Business Manager etc: Intel Cisco Dell Leobit CSHARK Brainvire Brainhub Capgemini Many more… So, you could be the next potential employee for any of these major companies. Start learning VB.Net using our simple and effective tutorial anywhere and anytime absolutely at your pace. Frequently Asked Questions about VB.Net In this section, we will try to answer some of the Frequently Asked Questions(FAQ) about VB.Net: What is the difference between VB and VB.Net? Visual Basic is an event-driven programming language that was first released in 1991. On the other hand, VB.Net is an object-oriented programming language introduced by Microsoft in 2002 as part of the .NET framework. What do you mean by JIT? JIT stands for Just-In-Time compilation. It is a part of the runtime execution environment in .NET and is used to optimize the performance. What is TRACE in VB.Net? Trace is a class of the System.Diagnostics namespace. It provides methods to display information about the execution of programs. What are class access modifiers? Class access modifiers in VB.Net are keywords used to control the accessibility of classes and their members. There are six access modifiers which are Public, Private, Protected, Friend, Protected Friend, and Private Protected. What is the base class of VB.NET? The base class for all classes in VB.NET is the Object class. What is delegates in VB.NET? Delegates in VB.NET are similar to function pointers in C or C++ programming languages. They are used to encapsulate a reference to a method. What is Common Language Runtime or CLR? The Common Language Runtime (CLR) is the virtual machine component of the .NET framework. It provides various services including garbage collection, security, and exception handling. What exactly is garbage collection? Garbage collection in .NET is the process of automatically freeing memory occupied by objects that are no longer in use. What is Global Assembly Cache? The Global Assembly Cache (GAC) is a machine-wide code cache that stores .NET assemblies, which can be shared by several applications on the computer. What is jagged array in VB.Net? A jagged array in VB.Net is an array of arrays, where each inner array can be of different lengths. Print Page Previous Next Advertisements ”;

VB.Net – Excel Sheet

VB.Net – Excel Sheet ”; Previous Next VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application. To avail this interoperability in your application, you need to import the namespace Microsoft.Office.Interop.Excel in your Windows Form Application. Creating an Excel Application from VB.Net Let”s start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File → New Project → Windows Forms Applications Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1. Insert a Button control Button1 in the form. Add a reference to Microsoft Excel Object Library to your project. To do this − Select Add Reference from the Project Menu. On the COM tab, locate Microsoft Excel Object Library and then click Select. Click OK. Double click the code window and populate the Click event of Button1, as shown below. ” Add the following code snippet on top of Form1.vb Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim appXL As Excel.Application Dim wbXl As Excel.Workbook Dim shXL As Excel.Worksheet Dim raXL As Excel.Range ” Start Excel and get Application object. appXL = CreateObject(“Excel.Application”) appXL.Visible = True ” Add a new workbook. wbXl = appXL.Workbooks.Add shXL = wbXl.ActiveSheet ” Add table headers going cell by cell. shXL.Cells(1, 1).Value = “First Name” shXL.Cells(1, 2).Value = “Last Name” shXL.Cells(1, 3).Value = “Full Name” shXL.Cells(1, 4).Value = “Specialization” ” Format A1:D1 as bold, vertical alignment = center. With shXL.Range(“A1”, “D1″) .Font.Bold = True .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter End With ” Create an array to set multiple values at once. Dim students(5, 2) As String students(0, 0) = “Zara” students(0, 1) = “Ali” students(1, 0) = “Nuha” students(1, 1) = “Ali” students(2, 0) = “Arilia” students(2, 1) = “RamKumar” students(3, 0) = “Rita” students(3, 1) = “Jones” students(4, 0) = “Umme” students(4, 1) = “Ayman” ” Fill A2:B6 with an array of values (First and Last Names). shXL.Range(“A2”, “B6″).Value = students ” Fill C2:C6 with a relative formula (=A2 & ” ” & B2). raXL = shXL.Range(“C2”, “C6”) raXL.Formula = “=A2 & “” “” & B2″ ” Fill D2:D6 values. With shXL .Cells(2, 4).Value = “Biology” .Cells(3, 4).Value = “Mathmematics” .Cells(4, 4).Value = “Physics” .Cells(5, 4).Value = “Mathmematics” .Cells(6, 4).Value = “Arabic” End With ” AutoFit columns A:D. raXL = shXL.Range(“A1”, “D1″) raXL.EntireColumn.AutoFit() ” Make sure Excel is visible and give the user control ” of Excel”s lifetime. appXL.Visible = True appXL.UserControl = True ” Release object references. raXL = Nothing shXL = Nothing wbXl = Nothing appXL.Quit() appXL = Nothing Exit Sub Err_Handler: MsgBox(Err.Description, vbCritical, “Error: ” & Err.Number) 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 − Clicking on the Button would display the following excel sheet. You will be asked to save the workbook. Print Page Previous Next Advertisements ”;

VB.Net – Functions

VB.Net – Functions ”; Previous Next A procedure is a group of statements that together perform a task when called. After the procedure is executed, the control returns to the statement calling the procedure. VB.Net has two types of procedures − Functions Sub procedures or Subs Functions return a value, whereas Subs do not return a value. Defining a Function The Function statement is used to declare the name, parameter and the body of a function. The syntax for the Function statement is − [Modifiers] Function FunctionName [(ParameterList)] As ReturnType [Statements] End Function Where, Modifiers − specify the access level of the function; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing. FunctionName − indicates the name of the function ParameterList − specifies the list of the parameters ReturnType − specifies the data type of the variable the function returns Example Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer ” local variable declaration */ Dim result As Integer If (num1 > num2) Then result = num1 Else result = num2 End If FindMax = result End Function Function Returning a Value In VB.Net, a function can return a value to the calling code in two ways − By using the return statement By assigning the value to the function name The following example demonstrates using the FindMax function − Live Demo Module myfunctions Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer ” local variable declaration */ Dim result As Integer If (num1 > num2) Then result = num1 Else result = num2 End If FindMax = result End Function Sub Main() Dim a As Integer = 100 Dim b As Integer = 200 Dim res As Integer res = FindMax(a, b) Console.WriteLine(“Max value is : {0}”, res) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Max value is : 200 Recursive Function A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function − Live Demo Module myfunctions Function factorial(ByVal num As Integer) As Integer ” local variable declaration */ Dim result As Integer If (num = 1) Then Return 1 Else result = factorial(num – 1) * num Return result End If End Function Sub Main() ”calling the factorial method Console.WriteLine(“Factorial of 6 is : {0}”, factorial(6)) Console.WriteLine(“Factorial of 7 is : {0}”, factorial(7)) Console.WriteLine(“Factorial of 8 is : {0}”, factorial(8)) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320 Param Arrays At times, while declaring a function or sub procedure, you are not sure of the number of arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at these times. The following example demonstrates this − Live Demo Module myparamfunc Function AddElements(ParamArray arr As Integer()) As Integer Dim sum As Integer = 0 Dim i As Integer = 0 For Each i In arr sum += i Next i Return sum End Function Sub Main() Dim sum As Integer sum = AddElements(512, 720, 250, 567, 889) Console.WriteLine(“The sum is: {0}”, sum) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − The sum is: 2938 Passing Arrays as Function Arguments You can pass an array as a function argument in VB.Net. The following example demonstrates this − Live Demo Module arrayParameter Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double ”local variables Dim i As Integer Dim avg As Double Dim sum As Integer = 0 For i = 0 To size – 1 sum += arr(i) Next i avg = sum / size Return avg End Function Sub Main() ” an int array with 5 elements ” Dim balance As Integer() = {1000, 2, 3, 17, 50} Dim avg As Double ”pass pointer to the array as an argument avg = getAverage(balance, 5) ” output the returned value ” Console.WriteLine(“Average value is: {0} “, avg) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Average value is: 214.4 Print Page Previous Next Advertisements ”;

VB.Net – Advanced Forms

VB.Net – Advanced Form ”; Previous Next In this chapter, let us study the following concepts − Adding menus and sub menus in an application Adding the cut, copy and paste functionalities in a form Anchoring and docking controls in a form Modal forms Adding Menus and Sub Menus in an Application Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were used for adding menus, sub-menus and context menus in a Windows application. Now, the MenuStrip, the ToolStripMenuItem, ToolStripDropDown and ToolStripDropDownMenu controls replace and add functionality to the Menu-related controls of previous versions. However, the old control classes are retained for both backward compatibility and future use. Let us create a typical windows main menu bar and sub menus using the old version controls first since these controls are still much used in old applications. Following is an example, which shows how we create a menu bar with menu items: File, Edit, View and Project. The File menu has the sub menus New, Open and Save. Let”s double click on the Form and put the following code in the opened window. Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ”defining the main menu bar Dim mnuBar As New MainMenu() ”defining the menu items for the main menu bar Dim myMenuItemFile As New MenuItem(“&File”) Dim myMenuItemEdit As New MenuItem(“&Edit”) Dim myMenuItemView As New MenuItem(“&View”) Dim myMenuItemProject As New MenuItem(“&Project”) ”adding the menu items to the main menu bar mnuBar.MenuItems.Add(myMenuItemFile) mnuBar.MenuItems.Add(myMenuItemEdit) mnuBar.MenuItems.Add(myMenuItemView) mnuBar.MenuItems.Add(myMenuItemProject) ” defining some sub menus Dim myMenuItemNew As New MenuItem(“&New”) Dim myMenuItemOpen As New MenuItem(“&Open”) Dim myMenuItemSave As New MenuItem(“&Save”) ”add sub menus to the File menu myMenuItemFile.MenuItems.Add(myMenuItemNew) myMenuItemFile.MenuItems.Add(myMenuItemOpen) myMenuItemFile.MenuItems.Add(myMenuItemSave) ”add the main menu to the form Me.Menu = mnuBar ” Set the caption bar text of the form. Me.Text = “tutorialspoint.com” 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 − Windows Forms contain a rich set of classes for creating your own custom menus with modern appearance, look and feel. The MenuStrip, ToolStripMenuItem, ContextMenuStrip controls are used to create menu bars and context menus efficiently. Click the following links to check their details − Sr.No. Control & Description 1 MenuStrip It provides a menu system for a form. 2 ToolStripMenuItem It represents a selectable option displayed on a MenuStrip or ContextMenuStrip. The ToolStripMenuItem control replaces and adds functionality to the MenuItem control of previous versions. 3 ContextMenuStrip It represents a shortcut menu. Adding the Cut, Copy and Paste Functionalities in a Form The methods exposed by the ClipBoard class are used for adding the cut, copy and paste functionalities in an application. The ClipBoard class provides methods to place data on and retrieve data from the system Clipboard. It has the following commonly used methods − Sr.No. Method Name & Description 1 Clear Removes all data from the Clipboard. 2 ContainsData Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format. 3 ContainsImage Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format. 4 ContainsText Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system. 5 GetData Retrieves data from the Clipboard in the specified format. 6 GetDataObject Retrieves the data that is currently on the system Clipboard. 7 GetImage Retrieves an image from the Clipboard. 8 GetText Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system. 9 GetText(TextDataFormat) Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value. 10 SetData Clears the Clipboard and then adds data in the specified format. 11 SetText(String) Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system. Following is an example, which shows how we cut, copy and paste data using methods of the Clipboard class. Take the following steps − Add a rich text box control and three button controls on the form. Change the text property of the buttons to Cut, Copy and Paste, respectively. Double click on the buttons to add the following code in the code editor − 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 = “tutorialspoint.com” End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Clipboard.SetDataObject(RichTextBox1.SelectedText) RichTextBox1.SelectedText = “” End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) _ Handles Button2.Click Clipboard.SetDataObject(RichTextBox1.SelectedText) End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) _ Handles Button3.Click Dim iData As IDataObject iData = Clipboard.GetDataObject() If (iData.GetDataPresent(DataFormats.Text)) Then RichTextBox1.SelectedText = iData.GetData(DataFormats.Text) Else RichTextBox1.SelectedText = ” ” End If 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 − Enter some text and check how the buttons work. Anchoring and Docking Controls in a Form Anchoring allows you to set an anchor position for a control to the edges of its container control, for example, the form. The Anchor property of the Control class allows you to set values of this property. The Anchor property gets or sets the edges of the container to which a control is bound and determines how a control is resized with its parent. When you anchor a control to a form, the control maintains its distance from the edges of the form and its anchored position, when the form is resized. You can set the Anchor property values of a control from the Properties window − For example, let us add a Button control on a form and set its anchor property to Bottom, Right. Run this form to see the original position of the Button control with respect

VB.Net – Basic Controls

VB.Net – Basic Controls ”; Previous Next An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control consists of three important elements − Properties which describe the object, Methods cause an object to do something and Events are what happens when an object does something. Control Properties All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color. Properties can be set at design time by using the Properties window or at run time by using statements in the program code. Object. Property = Value Where Object is the name of the object you”re customizing. Property is the characteristic you want to change. Value is the new property setting. For example, Form1.Caption = “Hello” You can set any of the form properties using Properties Window. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them. Control Methods A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes − If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used. If none of the existing methods can perform your desired task, you can add a method to a class. For example, the MessageBox control has a method named Show, which is called in the code snippet below − Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show(“Hello, World”) End Sub End Class Control Events An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load, resize, etc. Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control − Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ”event handler code goes here End Sub Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way, you can check stub code for click, double click. If you want to initialize some variables like properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point to note is the name of the event handler, which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming. Basic Controls VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in the System.Windows.Forms namespace. The following table lists some of the commonly used controls − Sr.No. Widget & Description 1 Forms The container for all the controls that make up the user interface. 2 TextBox It represents a Windows text box control. 3 Label It represents a standard Windows label. 4 Button It represents a Windows button control. 5 ListBox It represents a Windows control to display a list of items. 6 ComboBox It represents a Windows combo box control. 7 RadioButton It enables the user to select a single option from a group of choices when paired with other RadioButton controls. 8 CheckBox It represents a Windows CheckBox. 9 PictureBox It represents a Windows picture box control for displaying an image. 10 ProgressBar It represents a Windows progress bar control. 11 ScrollBar It Implements the basic functionality of a scroll bar control. 12 DateTimePicker It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format. 13 TreeView It displays a hierarchical collection of labeled items, each represented by a TreeNode. 14 ListView It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views. Print Page Previous Next Advertisements ”;

VB.Net – XML Processing

VB.Net – XML Processing ”; Previous Next The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. The System.Xml namespace in the .Net Framework contains classes for processing XML documents. Following are some of the commonly used classes in the System.Xml namespace. Sr.No. Class & Description 1 XmlAttribute Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema. 2 XmlCDataSection Represents a CDATA section. 3 XmlCharacterData Provides text manipulation methods that are used by several classes. 4 XmlComment Represents the content of an XML comment. 5 XmlConvert Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale independent. 6 XmlDeclaration Represents the XML declaration node <?xml version=”1.0”…?>. 7 XmlDictionary Implements a dictionary used to optimize Windows Communication Foundation (WCF)”s XML reader/writer implementations. 8 XmlDictionaryReader An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization. 9 XmlDictionaryWriter Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization. 10 XmlDocument Represents an XML document. 11 XmlDocumentFragment Represents a lightweight object that is useful for tree insert operations. 12 XmlDocumentType Represents the document type declaration. 13 XmlElement Represents an element. 14 XmlEntity Represents an entity declaration, such as <!ENTITY… >. 15 XmlEntityReference Represents an entity reference node. 16 XmlException Returns detailed information about the last exception. 17 XmlImplementation Defines the context for a set of XmlDocument objects. 18 XmlLinkedNode Gets the node immediately preceding or following this node. 19 XmlNode Represents a single node in the XML document. 20 XmlNodeList Represents an ordered collection of nodes. 21 XmlNodeReader Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode. 22 XmlNotation Represents a notation declaration, such as <!NOTATION… >. 23 XmlParserContext Provides all the context information required by the XmlReader to parse an XML fragment. 24 XmlProcessingInstruction Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document. 25 XmlQualifiedName Represents an XML qualified name. 26 XmlReader Represents a reader that provides fast, noncached, forward-only access to XML data. 27 XmlReaderSettings Specifies a set of features to support on the XmlReader object created by the Create method. 28 XmlResolver Resolves external XML resources named by a Uniform Resource Identifier (URI). 29 XmlSecureResolver Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to. 30 XmlSignificantWhitespace Represents white space between markup in a mixed content node or white space within an xml:space= ”preserve” scope. This is also referred to as significant white space. 31 XmlText Represents the text content of an element or attribute. 32 XmlTextReader Represents a reader that provides fast, non-cached, forward-only access to XML data. 33 XmlTextWriter Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations. 34 XmlUrlResolver Resolves external XML resources named by a Uniform Resource Identifier (URI). 35 XmlWhitespace Represents white space in element content. 36 XmlWriter Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data. 37 XmlWriterSettings Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method. XML Parser APIs The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces. Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory. Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX obviously can”t process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files. SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can”t use them both for large projects. For all our XML code examples, let”s use a simple XML file movies.xml as an input − <?xml version = “1.0”?> <collection shelf = “New Arrivals”> <movie title = “Enemy Behind”> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = “Transformers”> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = “Trigun”> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title = “Ishtar”> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> Parsing XML with SAX API In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data. The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It reads an XML document or a stream. Example 1 This example demonstrates reading XML data from the file movies.xml. Take the following steps − Add the movies.xml file in the binDebug folder of your application. Import the System.Xml namespace in Form1.vb file. Add a label in the form and change its text to ”Movies Galore”. Add three list boxes and three buttons to show the title, type and description of a movie from the xml file. Add the following code using the code editor window. Imports System.Xml Public Class Form1 Private Sub Form1_Load(sender As Object, e As

VB.Net – Classes & Objects

VB.Net – Classes & Objects ”; Previous Next When you define a class, you define a blueprint for a data type. This doesn”t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class. Class Definition A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition − [ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _ Class name [ ( Of typelist ) ] [ Inherits classname ] [ Implements interfacenames ] [ statements ] End Class Where, attributelist is a list of attributes that apply to the class. Optional. accessmodifier defines the access levels of the class, it has values as – Public, Protected, Friend, Protected Friend and Private. Optional. Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional. MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional. NotInheritable specifies that the class cannot be used as a base class. Partial indicates a partial definition of the class. Inherits specifies the base class it is inheriting from. Implements specifies the interfaces the class is inheriting from. The following example demonstrates a Box class, with three data members, length, breadth and height − Live Demo Module mybox Class Box Public length As Double ” Length of a box Public breadth As Double ” Breadth of a box Public height As Double ” Height of a box End Class Sub Main() Dim Box1 As Box = New Box() ” Declare Box1 of type Box Dim Box2 As Box = New Box() ” Declare Box2 of type Box Dim volume As Double = 0.0 ” Store the volume of a box here ” box 1 specification Box1.height = 5.0 Box1.length = 6.0 Box1.breadth = 7.0 ” box 2 specification Box2.height = 10.0 Box2.length = 12.0 Box2.breadth = 13.0 ”volume of box 1 volume = Box1.height * Box1.length * Box1.breadth Console.WriteLine(“Volume of Box1 : {0}”, volume) ”volume of box 2 volume = Box2.height * Box2.length * Box2.breadth Console.WriteLine(“Volume of Box2 : {0}”, volume) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Member Functions and Encapsulation A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member and has access to all the members of a class for that object. Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions. Let us put above concepts to set and get the value of different class members in a class − Live Demo Module mybox Class Box Public length As Double ” Length of a box Public breadth As Double ” Breadth of a box Public height As Double ” Height of a box Public Sub setLength(ByVal len As Double) length = len End Sub Public Sub setBreadth(ByVal bre As Double) breadth = bre End Sub Public Sub setHeight(ByVal hei As Double) height = hei End Sub Public Function getVolume() As Double Return length * breadth * height End Function End Class Sub Main() Dim Box1 As Box = New Box() ” Declare Box1 of type Box Dim Box2 As Box = New Box() ” Declare Box2 of type Box Dim volume As Double = 0.0 ” Store the volume of a box here ” box 1 specification Box1.setLength(6.0) Box1.setBreadth(7.0) Box1.setHeight(5.0) ”box 2 specification Box2.setLength(12.0) Box2.setBreadth(13.0) Box2.setHeight(10.0) ” volume of box 1 volume = Box1.getVolume() Console.WriteLine(“Volume of Box1 : {0}”, volume) ”volume of box 2 volume = Box2.getVolume() Console.WriteLine(“Volume of Box2 : {0}”, volume) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Constructors and Destructors A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type. Following program explains the concept of constructor − Live Demo Class Line Private length As Double ” Length of a line Public Sub New() ”constructor Console.WriteLine(“Object is being created”) End Sub Public Sub setLength(ByVal len As Double) length = len End Sub Public Function getLength() As Double Return length End Function Shared Sub Main() Dim line As Line = New Line() ”set line length line.setLength(6.0) Console.WriteLine(“Length of line : {0}”, line.getLength()) Console.ReadKey() End Sub End Class When the above code is compiled and executed, it produces the following result − Object is being created Length of line : 6 A default constructor does not have any parameter, but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example − Live Demo Class Line Private length As Double ” Length of a line Public Sub New(ByVal len As Double) ”parameterised constructor Console.WriteLine(“Object is being created, length = {0}”, len) length = len End Sub Public Sub setLength(ByVal len As Double) length = len End Sub Public Function getLength() As Double Return length End Function Shared Sub Main() Dim line As Line

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