Discuss VB.Net ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Category: vb.net
VB.Net – Strings
VB.Net – Strings ”; Previous Next In VB.Net, you can use strings as array of characters, however, more common practice is to use the String keyword to declare a string variable. The string keyword is an alias for the System.String class. Creating a String Object You can create string object using one of the following methods − By assigning a string literal to a String variable By using a String class constructor By using the string concatenation operator (+) By retrieving a property or calling a method that returns a string By calling a formatting method to convert a value or object to its string representation The following example demonstrates this − Live Demo Module strings Sub Main() Dim fname, lname, fullname, greetings As String fname = “Rowan” lname = “Atkinson” fullname = fname + ” ” + lname Console.WriteLine(“Full Name: {0}”, fullname) ”by using string constructor Dim letters As Char() = {“H”, “e”, “l”, “l”, “o”} greetings = New String(letters) Console.WriteLine(“Greetings: {0}”, greetings) ”methods returning String Dim sarray() As String = {“Hello”, “From”, “Tutorials”, “Point”} Dim message As String = String.Join(” “, sarray) Console.WriteLine(“Message: {0}”, message) ”formatting method to convert a value Dim waiting As DateTime = New DateTime(2012, 12, 12, 17, 58, 1) Dim chat As String = String.Format(“Message sent at {0:t} on {0:D}”, waiting) Console.WriteLine(“Message: {0}”, chat) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Full Name: Rowan Atkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, December 12, 2012 Properties of the String Class The String class has the following two properties − Sr.No Property Name & Description 1 Chars Gets the Char object at a specified position in the current String object. 2 Length Gets the number of characters in the current String object. Methods of the String Class The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods − Sr.No Method Name & Description 1 Public Shared Function Compare ( strA As String, strB As String ) As Integer Compares two specified string objects and returns an integer that indicates their relative position in the sort order. 2 Public Shared Function Compare ( strA As String, strB As String, ignoreCase As Boolean ) As Integer Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true. 3 Public Shared Function Concat ( str0 As String, str1 As String ) As String Concatenates two string objects. 4 Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As String Concatenates three string objects. 5 Public Shared Function Concat (str0 As String, str1 As String, str2 As String, str3 As String ) As String Concatenates four string objects. 6 Public Function Contains ( value As String ) As Boolean Returns a value indicating whether the specified string object occurs within this string. 7 Public Shared Function Copy ( str As String ) As String Creates a new String object with the same value as the specified string. 8 pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Integer ) Copies a specified number of characters from a specified position of the string object to a specified position in an array of Unicode characters. 9 Public Function EndsWith ( value As String ) As Boolean Determines whether the end of the string object matches the specified string. 10 Public Function Equals ( value As String ) As Boolean Determines whether the current string object and the specified string object have the same value. 11 Public Shared Function Equals ( a As String, b As String ) As Boolean Determines whether two specified string objects have the same value. 12 Public Shared Function Format ( format As String, arg0 As Object ) As String Replaces one or more format items in a specified string with the string representation of a specified object. 13 Public Function IndexOf ( value As Char ) As Integer Returns the zero-based index of the first occurrence of the specified Unicode character in the current string. 14 Public Function IndexOf ( value As String ) As Integer Returns the zero-based index of the first occurrence of the specified string in this instance. 15 Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position. 16 Public Function IndexOf ( value As String, startIndex As Integer ) As Integer Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position. 17 Public Function IndexOfAny ( anyOf As Char() ) As Integer Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 18 Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position. 19 Public Function Insert ( startIndex As Integer, value As String ) As String Returns a new string in which a specified string is inserted at a specified index position in the current string object. 20 Public Shared Function IsNullOrEmpty ( value As String ) As Boolean Indicates whether the specified string is null or an Empty string. 21 Public Shared Function Join ( separator As String, ParamArray value As String() ) As String Concatenates all the elements of a string array, using the specified separator between each element. 22 Public Shared Function Join ( separator As String, value As String(), startIndex As Integer, count As Integer ) As
VB.Net – Regular Expressions
VB.Net – Regular Expressions ”; Previous Next A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs. Constructs for Defining Regular Expressions There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the following links to find these constructs. Character escapes Character classes Anchors Grouping constructs Quantifiers Backreference constructs Alternation constructs Substitutions Miscellaneous constructs The Regex Class The Regex class is used for representing a regular expression. The Regex class has the following commonly used methods − Sr.No. Methods & Description 1 Public Function IsMatch (input As String) As Boolean Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string. 2 Public Function IsMatch (input As String, startat As Integer ) As Boolean Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string. 3 Public Shared Function IsMatch (input As String, pattern As String ) As Boolean Indicates whether the specified regular expression finds a match in the specified input string. 4 Public Function Matches (input As String) As MatchCollection Searches the specified input string for all occurrences of a regular expression. 5 Public Function Replace (input As String, replacement As String) As String In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string. 6 Public Function Split (input As String) As String() Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor. For the complete list of methods and properties, please consult Microsoft documentation. Example 1 The following example matches words that start with ”S” − Live Demo Imports System.Text.RegularExpressions Module regexProg Sub showMatch(ByVal text As String, ByVal expr As String) Console.WriteLine(“The Expression: ” + expr) Dim mc As MatchCollection = Regex.Matches(text, expr) Dim m As Match For Each m In mc Console.WriteLine(m) Next m End Sub Sub Main() Dim str As String = “A Thousand Splendid Suns” Console.WriteLine(“Matching words that start with ”S”: “) showMatch(str, “bSS*”) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Matching words that start with ”S”: The Expression: bSS* Splendid Suns Example 2 The following example matches words that start with ”m” and ends with ”e” − Live Demo Imports System.Text.RegularExpressions Module regexProg Sub showMatch(ByVal text As String, ByVal expr As String) Console.WriteLine(“The Expression: ” + expr) Dim mc As MatchCollection = Regex.Matches(text, expr) Dim m As Match For Each m In mc Console.WriteLine(m) Next m End Sub Sub Main() Dim str As String = “make a maze and manage to measure it” Console.WriteLine(“Matching words that start with ”m” and ends with ”e”: “) showMatch(str, “bmS*eb”) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Matching words start with ”m” and ends with ”e”: The Expression: bmS*eb make maze manage measure Example 3 This example replaces extra white space − Live Demo Imports System.Text.RegularExpressions Module regexProg Sub Main() Dim input As String = “Hello World ” Dim pattern As String = “\s+” Dim replacement As String = ” ” Dim rgx As Regex = New Regex(pattern) Dim result As String = rgx.Replace(input, replacement) Console.WriteLine(“Original String: {0}”, input) Console.WriteLine(“Replacement String: {0}”, result) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Original String: Hello World Replacement String: Hello World Print Page Previous Next Advertisements ”;
VB.Net – Arrays
VB.Net – Arrays ”; Previous Next An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Creating Arrays in VB.Net To declare an array in VB.Net, you use the Dim statement. For example, Dim intData(30) ” an array of 31 elements Dim strData(20) As String ” an array of 21 strings Dim twoDarray(10, 20) As Integer ”a two dimensional array of integers Dim ranges(10, 100) ”a two dimensional array You can also initialize the array elements while declaring the array. For example, Dim intData() As Integer = {12, 16, 20, 24, 28, 32} Dim names() As String = {“Karthik”, “Sandhya”, _ “Shivangi”, “Ashwitha”, “Somnath”} Dim miscData() As Object = {“Hello World”, 12d, 16ui, “A”c} The elements in an array can be stored and accessed by using the index of the array. The following program demonstrates this − Live Demo Module arrayApl Sub Main() Dim n(10) As Integer ” n is an array of 11 integers ” Dim i, j As Integer ” initialize elements of array n ” For i = 0 To 10 n(i) = i + 100 ” set element at location i to i + 100 Next i ” output each array element”s value ” For j = 0 To 10 Console.WriteLine(“Element({0}) = {1}”, j, n(j)) Next j Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Element(0) = 100 Element(1) = 101 Element(2) = 102 Element(3) = 103 Element(4) = 104 Element(5) = 105 Element(6) = 106 Element(7) = 107 Element(8) = 108 Element(9) = 109 Element(10) = 110 Dynamic Arrays Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare a dynamic array using the ReDim statement. Syntax for ReDim statement − ReDim [Preserve] arrayname(subscripts) Where, The Preserve keyword helps to preserve the data in an existing array, when you resize it. arrayname is the name of the array to re-dimension. subscripts specifies the new dimension. Module arrayApl Sub Main() Dim marks() As Integer ReDim marks(2) marks(0) = 85 marks(1) = 75 marks(2) = 90 ReDim Preserve marks(10) marks(3) = 80 marks(4) = 76 marks(5) = 92 marks(6) = 99 marks(7) = 79 marks(8) = 75 For i = 0 To 10 Console.WriteLine(i & vbTab & marks(i)) Next i Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − 0 85 1 75 2 90 3 80 4 76 5 92 6 99 7 79 8 75 9 0 10 0 Multi-Dimensional Arrays VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays. You can declare a 2-dimensional array of strings as − Dim twoDStringArray(10, 20) As String or, a 3-dimensional array of Integer variables − Dim threeDIntArray(10, 10, 10) As Integer The following program demonstrates creating and using a 2-dimensional array − Live Demo Module arrayApl Sub Main() ” an array with 5 rows and 2 columns Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}} Dim i, j As Integer ” output each array element”s value ” For i = 0 To 4 For j = 0 To 1 Console.WriteLine(“a[{0},{1}] = {2}”, i, j, a(i, j)) Next j Next i Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − a[0,0]: 0 a[0,1]: 0 a[1,0]: 1 a[1,1]: 2 a[2,0]: 2 a[2,1]: 4 a[3,0]: 3 a[3,1]: 6 a[4,0]: 4 a[4,1]: 8 Jagged Array A Jagged array is an array of arrays. The following code shows declaring a jagged array named scores of Integers − Dim scores As Integer()() = New Integer(5)(){} The following example illustrates using a jagged array − Live Demo Module arrayApl Sub Main() ”a jagged array of 5 array of integers Dim a As Integer()() = New Integer(4)() {} a(0) = New Integer() {0, 0} a(1) = New Integer() {1, 2} a(2) = New Integer() {2, 4} a(3) = New Integer() {3, 6} a(4) = New Integer() {4, 8} Dim i, j As Integer ” output each array element”s value For i = 0 To 4 For j = 0 To 1 Console.WriteLine(“a[{0},{1}] = {2}”, i, j, a(i)(j)) Next j Next i Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 The Array Class The Array class is the base class for all the arrays in VB.Net. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays. Properties of the Array Class The following table provides some of the most commonly used properties of the Array class − Sr.No Property Name & Description 1 IsFixedSize Gets a value indicating whether the Array has a fixed size. 2 IsReadOnly Gets a value indicating whether the Array is read-only. 3 Length Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. 4 LongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. 5 Rank Gets the rank (number of dimensions) of the Array. Methods of the Array Class The following table provides some of the most commonly used methods of the Array class − Sr.No Method Name & Description 1 Public Shared Sub Clear (array As Array, index As Integer, length As Integer) Sets a range of elements in the Array to zero, to false, or to null, depending on the element
VB.Net – Send Email
VB.Net – Send Email ”; Previous Next VB.Net allows sending e-mails from your application. The System.Net.Mail namespace contains classes used for sending e-mails to a Simple Mail Transfer Protocol (SMTP) server for delivery. The following table lists some of these commonly used classes − Sr.No. Class & Description 1 Attachment Represents an attachment to an e-mail. 2 AttachmentCollection Stores attachments to be sent as part of an e-mail message. 3 MailAddress Represents the address of an electronic mail sender or recipient. 4 MailAddressCollection Stores e-mail addresses that are associated with an e-mail message. 5 MailMessage Represents an e-mail message that can be sent using the SmtpClient class. 6 SmtpClient Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). 7 SmtpException Represents the exception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation. The SmtpClient Class The SmtpClient class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Following are some commonly used properties of the SmtpClient class − Sr.No. Property & Description 1 ClientCertificates Specifies which certificates should be used to establish the Secure Sockets Layer (SSL) connection. 2 Credentials Gets or sets the credentials used to authenticate the sender. 3 EnableSsl Specifies whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection. 4 Host Gets or sets the name or IP address of the host used for SMTP transactions. 5 Port Gets or sets the port used for SMTP transactions. 6 Timeout Gets or sets a value that specifies the amount of time after which a synchronous Send call times out. 7 UseDefaultCredentials Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests. Following are some commonly used methods of the SmtpClient class − Sr.No. Method & Description 1 Dispose Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class. 2 Dispose(Boolean) Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the SmtpClient class, and optionally disposes of the managed resources. 3 OnSendCompleted Raises the SendCompleted event. 4 Send(MailMessage) Sends the specified message to an SMTP server for delivery. 5 Send(String, String, String, String) Sends the specified e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. 6 SendAsync(MailMessage, Object) Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. 7 SendAsync(String, String, String, String, Object) Sends an e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. 8 SendAsyncCancel Cancels an asynchronous operation to send an e-mail message. 9 SendMailAsync(MailMessage) Sends the specified message to an SMTP server for delivery as an asynchronous operation. 10 SendMailAsync(String, String, String, String) Sends the specified message to an SMTP server for delivery as an asynchronous operation. . The message sender, recipients, subject, and message body are specified using String objects. 11 ToString Returns a string that represents the current object. The following example demonstrates how to send mail using the SmtpClient class. Following points are to be noted in this respect − You must specify the SMTP host server that you use to send e-mail. The Host and Port properties will be different for different host server. We will be using gmail server. You need to give the Credentials for authentication, if required by the SMTP server. You should also provide the email address of the sender and the e-mail address or addresses of the recipients using the MailMessage.From and MailMessage.To properties, respectively. You should also specify the message content using the MailMessage.Body property. Example In this example, let us create a simple application that would send an e-mail. 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 – ”From”, ”To:” and ”Message:” respectively. Change the name properties of the texts to txtFrom, txtTo and txtMessage respectively. Change the text property of the button control to ”Send” Add the following code in the code editor. Imports System.Net.Mail 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 Try Dim Smtp_Server As New SmtpClient Dim e_mail As New MailMessage() Smtp_Server.UseDefaultCredentials = False Smtp_Server.Credentials = New Net.NetworkCredential(“[email protected]”, “password”) Smtp_Server.Port = 587 Smtp_Server.EnableSsl = True Smtp_Server.Host = “smtp.gmail.com” e_mail = New MailMessage() e_mail.From = New MailAddress(txtFrom.Text) e_mail.To.Add(txtTo.Text) e_mail.Subject = “Email Sending” e_mail.IsBodyHtml = False e_mail.Body = txtMessage.Text Smtp_Server.Send(e_mail) MsgBox(“Mail Sent”) Catch error_t As Exception MsgBox(error_t.ToString) End Try End Sub You must provide your gmail address and real password for credentials. 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, which you will use to send your e-mails, try it yourself. Print Page Previous Next Advertisements ”;
VB.Net – Dialog Boxes
VB.Net – Dialog Boxes ”; Previous Next There are many built-in dialog boxes to be used in Windows forms for various tasks like opening and saving files, printing a page, providing choices for colors, fonts, page setup, etc., to the user of an application. These built-in dialog boxes reduce the developer”s time and workload. All of these dialog box control classes inherit from the CommonDialog class and override the RunDialog() function of the base class to create the specific dialog box. The RunDialog() function is automatically invoked when a user of a dialog box calls its ShowDialog() function. The ShowDialog method is used to display all the dialog box controls at run-time. It returns a value of the type of DialogResult enumeration. The values of DialogResult enumeration are − Abort − returns DialogResult.Abort value, when user clicks an Abort button. Cancel − returns DialogResult.Cancel, when user clicks a Cancel button. Ignore − returns DialogResult.Ignore, when user clicks an Ignore button. No − returns DialogResult.No, when user clicks a No button. None − returns nothing and the dialog box continues running. OK − returns DialogResult.OK, when user clicks an OK button Retry − returns DialogResult.Retry , when user clicks an Retry button Yes − returns DialogResult.Yes, when user clicks an Yes button The following diagram shows the common dialog class inheritance − All these above-mentioned classes have corresponding controls that could be added from the Toolbox during design time. You can include relevant functionality of these classes to your application, either by instantiating the class programmatically or by using relevant controls. When you double click any of the dialog controls in the toolbox or drag the control onto the form, it appears in the Component tray at the bottom of the Windows Forms Designer, they do not directly show up on the form. The following table lists the commonly used dialog box controls. Click the following links to check their detail − Sr.No. Control & Description 1 ColorDialog It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors. 2 FontDialog It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color. 3 OpenFileDialog It prompts the user to open a file and allows the user to select a file to open. 4 SaveFileDialog It prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. 5 PrintDialog It lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application. Print Page Previous Next Advertisements ”;
VB.Net – Constants
VB.Net – Constants and Enumerations ”; Previous Next The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. An enumeration is a set of named integer constants. Declaring Constants In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values. The syntax for the Const statement is − [ < attributelist > ] [ accessmodifier ] [ Shadows ] Const constantlist Where, attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional. accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private. Shadows − this makes the constant hide a programming element of identical name in a base class. Optional. Constantlist − gives the list of names of constants declared. Required. Where, each constant name has the following syntax and parts − constantname [ As datatype ] = initializer constantname − specifies the name of the constant datatype − specifies the data type of the constant initializer − specifies the value assigned to the constant For example, ”The following statements declare constants.” Const maxval As Long = 4999 Public Const message As String = “HELLO” Private Const piValue As Double = 3.1415 Example The following example demonstrates declaration and use of a constant value − Live Demo Module constantsNenum Sub Main() Const PI = 3.14149 Dim radius, area As Single radius = 7 area = PI * radius * radius Console.WriteLine(“Area = ” & Str(area)) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Area = 153.933 Print and Display Constants in VB.Net VB.Net provides the following print and display constants − Sr.No. Constant & Description 1 vbCrLf Carriage return/linefeed character combination. 2 vbCr Carriage return character. 3 vbLf Linefeed character. 4 vbNewLine Newline character. 5 vbNullChar Null character. 6 vbNullString Not the same as a zero-length string (“”); used for calling external procedures. 7 vbObjectError Error number. User-defined error numbers should be greater than this value. For example: Err.Raise(Number) = vbObjectError + 1000 8 vbTab Tab character. 9 vbBack Backspace character. Declaring Enumerations An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level. The syntax for the Enum statement is as follows − [ < attributelist > ] [ accessmodifier ] [ Shadows ] Enum enumerationname [ As datatype ] memberlist End Enum Where, attributelist − refers to the list of attributes applied to the variable. Optional. accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private. Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional. enumerationname − name of the enumeration. Required datatype − specifies the data type of the enumeration and all its members. memberlist − specifies the list of member constants being declared in this statement. Required. Each member in the memberlist has the following syntax and parts: [< attribute list >] member name [ = initializer ] Where, name − specifies the name of the member. Required. initializer − value assigned to the enumeration member. Optional. For example, Enum Colors red = 1 orange = 2 yellow = 3 green = 4 azure = 5 blue = 6 violet = 7 End Enum Example The following example demonstrates declaration and use of the Enum variable Colors − Live Demo Module constantsNenum Enum Colors red = 1 orange = 2 yellow = 3 green = 4 azure = 5 blue = 6 violet = 7 End Enum Sub Main() Console.WriteLine(“The Color Red is : ” & Colors.red) Console.WriteLine(“The Color Yellow is : ” & Colors.yellow) Console.WriteLine(“The Color Blue is : ” & Colors.blue) Console.WriteLine(“The Color Green is : ” & Colors.green) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − The Color Red is: 1 The Color Yellow is: 3 The Color Blue is: 6 The Color Green is: 4 Print Page Previous Next Advertisements ”;
VB.Net – Basic Syntax
VB.Net – Basic Syntax ”; Previous Next VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class. When we consider a VB.Net program, it can be defined as a collection of objects that communicate via invoking each other”s methods. Let us now briefly look into what do class, object, methods and instance variables mean. Object − Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behaviors – wagging, barking, eating, etc. An object is an instance of a class. Class − A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables − Each object has its unique set of instance variables. An object”s state is created by the values assigned to these instance variables. A Rectangle Class in VB.Net For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and displaying details. Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis of our observations in it − Live Demo Imports System Public Class Rectangle Private length As Double Private width As Double ”Public methods Public Sub AcceptDetails() length = 4.5 width = 3.5 End Sub Public Function GetArea() As Double GetArea = length * width End Function Public Sub Display() Console.WriteLine(“Length: {0}”, length) Console.WriteLine(“Width: {0}”, width) Console.WriteLine(“Area: {0}”, GetArea()) End Sub Shared Sub Main() Dim r As New Rectangle() r.Acceptdetails() r.Display() Console.ReadLine() End Sub End Class When the above code is compiled and executed, it produces the following result − Length: 4.5 Width: 3.5 Area: 15.75 In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both code and data. You use classes to create objects. For example, in the code, r is a Rectangle object. An object is an instance of a class − Dim r As New Rectangle() A class may have members that can be accessible from outside class, if so specified. Data members are called fields and procedure members are called methods. Shared methods or static methods can be invoked without creating an object of the class. Instance methods are invoked through an object of the class − Shared Sub Main() Dim r As New Rectangle() r.Acceptdetails() r.Display() Console.ReadLine() End Sub Identifiers An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in VB.Net are as follows − A name must begin with a letter that could be followed by a sequence of letters, digits (0 – 9) or underscore. The first character in an identifier cannot be a digit. It must not contain any embedded space or symbol like ? – +! @ # % ^ & * ( ) [ ] { } . ; : ” ” / and . However, an underscore ( _ ) can be used. It should not be a reserved keyword. VB.Net Keywords The following table lists the VB.Net reserved keywords − AddHandler AddressOf Alias And AndAlso As Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate CDec CDbl Char CInt Class CLng CObj Const Continue CSByte CShort CSng CStr CType CUInt CULng CUShort Date Decimal Declare Default Delegate Dim DirectCast Do Double Each Else ElseIf End End If Enum Erase Error Event Exit False Finally For Friend Function Get GetType GetXML Namespace Global GoTo Handles If Implements Imports In Inherits Integer Interface Is IsNot Let Lib Like Long Loop Me Mod Module MustInherit MustOverride MyBase MyClass Namespace Narrowing New Next Not Nothing Not Inheritable Not Overridable Object Of On Operator Option Optional Or OrElse Overloads Overridable Overrides ParamArray Partial Private Property Protected Public RaiseEvent ReadOnly ReDim REM Remove Handler Resume Return SByte Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throw To True Try TryCast TypeOf UInteger While Widening With WithEvents WriteOnly Xor Print Page Previous Next Advertisements ”;
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 ”;