Wednesday, February 29, 2012

VB.NET Input Box

An often used feature in classic Visual Basic is the InputBox function. It provides an easy way to prompt the user for simple text input. VB.NET carries this handy function forward for all to use. Although you probably won’t use this any time you need to request a large or amount of data or in other complex scenarios, it does provide a simple and effective way to get input in your Visual Basic.NET apps.

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a string containing the contents of the text box.

Usage :

stringvariable = InputBox(prompt[, title] [, default] [, xpos] [, ypos])

The arguments to the InputBox function are described below:

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.

Both optional. Numeric expressions that specify custom positioning of the box on screen (by default, the box is displayed in the center of the screen, which is usually desired).

Remarks

If the user clicks OK or presses ENTER , the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

Sample Program

The sample program uses a form with two buttons and a label, laid out as shown below:

image

The properties set for these controls are as follows:

(First Button):

Name: cmdGetInputText: Get Input

(Label):

Name: lblInfoAutoSize: FalseBackColor: KhakiBorderStyle: Fixed SingleText: (clear)

(Second Button):

The code for the program is shown below:

Public Class Form1 PrivateSub cmdGetInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetInput.Click Dim strUserName AsString  strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")  If strUserName = ""Then ' user cancelled the InputBox, so clear the label lblInfo.Text = "" Else lblInfo.Text = "User Name: " & strUserName EndIf EndSub  PrivateSub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() EndSubEnd Class

When the program is run and you click the "Get Input" button, the following input box is displayed. Note the content of the box based upon the values used as the arguments for the InputBox function:

        strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")

image

Enter your name in the text entry portion of the box (in this example, the name John is entered):

image

After you click OK, the text "User Name: " concatenated with the name you entered will be displayed in the label:

image

You can download the example code for this tutorial here: InputBox VB.NET Example

This article was original written by The VB Programmer.


View the original article here

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen () to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen () can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

VB.NET Input Box

An often used feature in classic Visual Basic is the InputBox function. It provides an easy way to prompt the user for simple text input. VB.NET carries this handy function forward for all to use. Although you probably won’t use this any time you need to request a large or amount of data or in other complex scenarios, it does provide a simple and effective way to get input in your Visual Basic.NET apps.

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a string containing the contents of the text box.

Usage :

stringvariable = InputBox(prompt[, title] [, default] [, xpos] [, ypos])

The arguments to the InputBox function are described below:

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.

Both optional. Numeric expressions that specify custom positioning of the box on screen (by default, the box is displayed in the center of the screen, which is usually desired).

Remarks

If the user clicks OK or presses ENTER , the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

Sample Program

The sample program uses a form with two buttons and a label, laid out as shown below:

image

The properties set for these controls are as follows:

(First Button):

Name: cmdGetInputText: Get Input

(Label):

Name: lblInfoAutoSize: FalseBackColor: KhakiBorderStyle: Fixed SingleText: (clear)

(Second Button):

The code for the program is shown below:

Public Class Form1 PrivateSub cmdGetInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetInput.Click Dim strUserName AsString  strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")  If strUserName = ""Then ' user cancelled the InputBox, so clear the label lblInfo.Text = "" Else lblInfo.Text = "User Name: " & strUserName EndIf EndSub  PrivateSub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() EndSubEnd Class

When the program is run and you click the "Get Input" button, the following input box is displayed. Note the content of the box based upon the values used as the arguments for the InputBox function:

        strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")

image

Enter your name in the text entry portion of the box (in this example, the name John is entered):

image

After you click OK, the text "User Name: " concatenated with the name you entered will be displayed in the label:

image

You can download the example code for this tutorial here: InputBox VB.NET Example

This article was original written by The VB Programmer.


View the original article here

Reading Text Files

A very common need when programming almost any application is the ability to read data from a text file. Fortunately VB.NET excels at this sort of thing. In the tutorial that follows we will show exactly how you can read through a text file, parse the information, and use it in your Visual Basic application. This can be combined with other articles on this site to handle storing and reading data.

A data file consists of records, which consist of fields. The file that will be used for all examples in this section is a simplified employee file, which consists of the following fields:

*Please note that the data types for these fields are the data types of the variables into which these fields will be stored.  In the text file, all fields will be represented as a string of characters.

Suppose there were five records in the file.  A graphic representation of the file populated with the five data records follows (the field names are not stored in the file):

Employee Name

(Last Name first)

There are two basic ways a file like this would typically come to you. The first way is in fixed-length format, where each field is stored in a fixed position.  On each record, a particular field starts and ends in the same position and occupies the same amount of space. The second way is in delimited format, where the fields within each record are separated from each other by a delimiter character. Commonly used delimiter characters are the tab (ASCII value 9), the "pipe" (vertical bar character "|"), and the comma (","). The comma-delimited file is probably the most commonly used (it is also referred to a "csv" file, where "csv" stands for "comma separated values") – however, there are certain considerations for comma-delimted files that must be taken into account; fortunately VB has an easy way to address these considerations.

The basic way to process both fixed-length files and delimited files is to read the file one line (record) at a time into a string variable, and then use string-handling methods to "break up" the data in the record into separate variables, where each variable represents a field of the record. However, in the case of delimited files, care must be taken to ensure that the data itself does not contain the delimiter character (because if it does, and your program does not handle this, you will wind up with misaligned fields and end-of-file errors). If using the tab (ASCII value 9), or another rarely-used character such as the pipe ("|"), chances are good that the data fields do not contain one of these characters – however, in the case of the comma-delimited file, some data fields may very well contain a comma – in which case the field will be enclosed in quotes. To handle the case of a comma-delimited file that contains fields enclosed in quotes, using native .NET methods, you would have to do extra string parsing to process the data correctly – however, there is a function in the MS.VB namespace that handles this parsing automatically for you, making it relatively easy to process such a file.

We will first look at examples that will process fixed-length files and delimited files using both the System.IO namespace techniques and the Microsoft.VisualBasic techniques. We will then look at an example that can easily handle a challenge brought about by comma-delimited files which contain fields enclosed in quotes.

In this example, for each record (line) of the file, each field starts and ends in the same position and occupies the same amount of space. The content of the file is shown below, along with a column position guide (highlighted in yellow) shown above the records.  From the example, it should be clear that the employee name occupies positions 1 through 20 of each record (note that names shorter than 20 characters are padded with blank spaces); the department number occupies positions 21 through 24 (right-justified and padded left with spaces – so while up to four digits are allowed, each record in this case uses only three digits); the job title occupies positions 30 through 50; the hire date occupies positions 51 through 60; and the hourly rate occupies positions 61 through 65.

image

First, let us introduce the new VB.NET elements that will be used in this example.

The input file ("employee_fixed.txt") will be located in the \bin\Debug subdirectory of your application directory. This is the directory where the executable version of your program is created and stored when you test or run your program from the development environment. This subdirectory can be referenced as follows:

        My.Application.Info.DirectoryPath

To refer to the input file with the full directory path, you concatenate a backslash ("\") along with the filename to the above reference:

        My.Application.Info.DirectoryPath & "\employee_fixed.txt"

(Note: "My.Application.Info.DirectoryPath" would be the equivalent of "App.Path" in pre-.NET versions of VB.) 

The FileStream class is used to create an object that will reference the file that will be processed by the program. The syntax for declaring a FileStream object, as it will be used in the examples that follow, is:

       Dim variable As New FileStream(path, mode, access [,share])

where

is a string that refers to the full path and filename of the file to be processed. As in the example above, you can use a reference like My.Application.Info.DirectoryPath & "\somefile.txt" or any other path/file reference, such as "C:\SomeDirectory\SomeFile.dat".

is an enumeration that specifies how the file should be open or created. The possible values are:

Opens the file if it exists and starts writing new data at the end of the file (preserving what is already there). If the file does not exist, it is created.

Creates a new file; if the file already exists, it is overwritten.

Creates a new file; if the file already exists, an exception is thrown.

Opens an existing file; if the file does not exist, an exception is thrown.

Opens a file if it exists, or creates a new file if it does not exist.

Opens an existing file and truncates it (i.e., deletes any data that was previously there).

is an enumeration that specifies how the file can be accessed. The possible values are:

Data can be read from the file, but not written to it.

Data can be read from and written to the file.

Data can be written to the file, but not read from it.

is an enumeration that specifies restrictions on how other processes can access the file. The possible values are:

Other processes may neither read from nor write to the file.

Any process can read from or write to the file.

Other processes may write to the file.

Other processes may read from the file.

Sample declaration:

Dim strFileName As String = My.Application.Info.DirectoryPath & "\employee_fixed.txt" Dim objFS As New FileStream(strFileName, FileMode.Open, FileAccess.Read)

In the above declaration, the filename was established in a separate string variable, which was then used as the path argument to the FileStream class. The resulting variable, objFS, is a FileStream object that refers to the file.

If desired, you could skip the separate declaration for the filename and write the declaration like this:

      Dim objFS As New FileStream(My.Application.Info.DirectoryPath & "\employee_fixed.txt", FileMode.Open, FileAccess.Read)

The StreamReader class is used to read a stream of characters. In the .NET framework, a stream, in general terms, is the flow of data from one location to another. In the case of these examples, a stream refers to the text file that will be processed by the sample programs. The syntax for declaring a StreamReader object is:

       Dim variable As New StreamReader(stream)

where

is an object representing the stream of characters to be read (in this case a text file).

Sample declaration:

Assuming the declaration of objFS as described above, the declaration could be written as follows: 

      Dim objSR As New StreamReader(objFS)

If desired, you could skip the separate declarations for the filename and FileStream and write the declaration like this:

Dim objSR As New StreamReader( _ New FileStream(My.Application.Info.DirectoryPath & "\employee_fixed.txt", _ FileMode.Open, FileAccess.Read))

Commonly used methods of the StreamReader class are:

Looks ahead to the next available character in the input stream without actually advancing to that next position. If no character is available, Peek returns -1. (This method is convenient to test for end-of-file.)

Reads the next character from the input stream.

Reads the next line of characters from the input stream into a string.

Reads the data from the current position in the input stream to the end of the stream into a string. (This method is often used to read the entire contents of a file.)

Closes the StreamReader and its associated FileStream object.

Code for sample program #1:

The following code reads the fixed-length format file as described above, record by record, and writes a formatted line containing the data from each record on the console.

Imports System.IO  Module Module1   Sub Main()  Dim strFileName AsString = My.Application.Info.DirectoryPath _ & "\employee_fixed.txt" Dim objFS AsNew FileStream(strFileName, FileMode.Open, FileAccess.Read) Dim objSR AsNew StreamReader(objFS)  Dim strEmpRecord AsString Dim strEmpName AsString Dim intDeptNbr AsInteger Dim strJobTitle AsString Dim dtmHireDate AsDate Dim sngHrlyRate AsSingle  Console.WriteLine("The records in the employee_fixed.txt file are:") Console.WriteLine("") Console.WriteLine("EMPLOYEE NAME".PadRight(20) _ & Space(3) _ & "DEPT" _ & Space(3) _ & "JOB TITLE".PadRight(21) _ & Space(3) _ & "HIRE DATE " _ & Space(3) _ & "HRLY RATE") Console.WriteLine("-------------".PadRight(20) _ & Space(3) _ & "----" _ & Space(3) _ & "---------".PadRight(21) _ & Space(3) _ & "--------- " _ & Space(3) _ & "---------")  DoWhile objSR.Peek <> -1 ' read the current record (line) into the variable strEmpRecord strEmpRecord = objSR.ReadLine  ' break up the record into separate variables strEmpName = strEmpRecord.Substring(0, 20) intDeptNbr = CInt(strEmpRecord.Substring(20, 4)) strJobTitle = strEmpRecord.Substring(29, 21) dtmHireDate = CDate(strEmpRecord.Substring(50, 10)) sngHrlyRate = CSng(strEmpRecord.Substring(60, 5))  ' Output the data to the console as a formatted line ... Console.WriteLine(strEmpName _ & Space(3) _ & intDeptNbr.ToString.PadLeft(4) _ & Space(3) _ & strJobTitle _ & Space(3) _ & Format(dtmHireDate, "MM/dd/yyyy") _ & Space(3) _ & Format(sngHrlyRate, "Currency").PadLeft(9)) Loop  objSR.Close()  Console.WriteLine("") Console.WriteLine("Press Enter to close this window.") Console.ReadLine()  EndSub End Module

When the above code is run, the following output is produced:

image

A synopsis of the code follows:

Note that first, your program must import the System.IO namespace. In the Main procedure, the FileStream and StreamReader objects are established, and variables to hold the record data and its constituent fields are declared. Several lines that serve as "headings" are then written to the console. The program then commences with the main processing loop that will process each record in the file, line by line. As long as there is data remaining in the file (as tested with the Peek method), a record is read from the file using the ReadLine method into the strEmpRecord variable. The data from the record is broken up into fields stored in separate variables using the SubString method. A formatted string using these field variables is then written to the console. When the main processing loop ends (i.e., the Peek method detects end-of-file), the StreamReader is closed, and the program ends with our standard message to close the console window.

Download the VB.NET project code for the example above: Read a Fixed Text File

In this example, the fields within each record (line) of the file are delimited by the pipe (|) character. The content of the file is shown below. Note that the fields are "trimmed", as the extra padding needed by the fixed-length format is not needed here.

image

As you will see in the code below, the basic process is the same, except instead of using the SubString method to break up the fields as we had to do to process the fixed-length format file, we will use the Split method to break up the fields for this pipe-delimited file.

Code for sample program #2:

The following code reads the pipe-delimited file as described above, record by record, and writes a formatted line containing the data from each record on the console. (This program produces the exact same output as the previous program.)

Imports System.IO  Module Module1   Sub Main()  Dim strFileName AsString = My.Application.Info.DirectoryPath _ & "\employee_pipe.txt" Dim objFS AsNew FileStream(strFileName, FileMode.Open, FileAccess.Read) Dim objSR AsNew StreamReader(objFS)  Dim strEmpRecord AsString Dim astrEmpFields() AsString  Console.WriteLine("The records in the employee_fixed.txt file are:") Console.WriteLine("") Console.WriteLine("EMPLOYEE NAME".PadRight(20) _ & Space(3) _ & "DEPT" _ & Space(3) _ & "JOB TITLE".PadRight(21) _ & Space(3) _ & "HIRE DATE " _ & Space(3) _ & "HRLY RATE") Console.WriteLine("-------------".PadRight(20) _ & Space(3) _ & "----" _ & Space(3) _ & "---------".PadRight(21) _ & Space(3) _ & "--------- " _ & Space(3) _ & "---------")  DoWhile objSR.Peek <> -1 ' read the current record (line) into the variable strEmpRecord strEmpRecord = objSR.ReadLine  ' break up the record into separate elements of the astrEmpFields array astrEmpFields = strEmpRecord.Split("|")  ' Output the data to the console as a formatted line ... Console.WriteLine(astrEmpFields(0).PadRight(20) _ & Space(3) _ & astrEmpFields(1).PadLeft(4) _ & Space(3) _ & astrEmpFields(2).PadRight(21) _ & Space(3) _ & Format(CDate(astrEmpFields(3)), "MM/dd/yyyy").PadRight(10) _ & Space(3) _ & Format(CSng(astrEmpFields(4)), "Currency").PadLeft(9)) Loop  objSR.Close()  Console.WriteLine("") Console.WriteLine("Press Enter to close this window.") Console.ReadLine()  EndSub End Module

A synopsis of the code follows:

As in the previous program, your program must import the System.IO namespace. In the Main procedure, the FileStream and StreamReader objects are established, and variables to hold the record data and a string array that will contain its constituent fields are declared. Several lines that serve as "headings" are then written to the console. The program then commences with the main processing loop that will process each record in the file, line by line. As long as there is data remaining in the file (as tested with the Peek method), a record is read from the file using the ReadLine method into the strEmpRecord variable. The data from the record is broken up into fields using the Split method, which will cause the data from the fields to be stored in elements of the astrEmpFields array. A formatted string using the array data is then written to the console. When the main processing loop ends (i.e., the Peek method detects end-of-file), the StreamReader is closed, and the program ends with our standard message to close the console window.

Download the VB.NET sample code for this example: Reading a pipe delimited file

In this example, the fields within each record (line) of the file are delimited by a comma (,). However, since the employee name field itself contains a comma, it is also enclosed in quotes. The content of the file is shown below.

image

The intention of the quotes is to tell the program that is to process this file to treat the data between the quotes as a single field, thus overriding the function of the comma in that case. If we had only the methods described thus far available to us, we would have to perform extra string parsing on the record after it had been read in with the ReadLine method of the StreamReader object – we could not simply use the Split method using the comma as the delimiter. Doing that would cause us to get an extra data item that we did not expect (i.e., two fields for the employee name instead of one), and furthermore, the quotes would be stored as part of the fields, which we also would not want. Fortunately, we can use the Input function available in the Microsoft.VisualBasic namespace to handle exactly this type of situation, as that is what it was designed to do. The MS.VB Input function is a retooled version of the Input statement that was available not only in classic VB, but prior to that in old versions of BASIC such as QBASIC and GW-BASIC.

In this example, we will also use some of the other Microsoft.VisualBasic namespace functions. The MS.VB namespace functions are summarized below, followed by more detailed explanations.

Returns an Integer value representing the next file number available for use by the FileOpen function. (Analagous to the FreeFile statement in classic VB.)  (Note: When using the MS.VB namespace functions, a file is referenced by a number rather than an object.)

Opens a file for input or output. (Analagous to the Open statement in classic VB.)

Reads a comma-delimited field from a text file and assigns it to a variable. (Analagous to the Input statement in classic VB.)

Reads a single line from an open sequential file and assigns it to a String variable. (Analagous to the LineInput statement in classic VB; also analagous to the ReadLine method of the StreamReader object.)

Reads a specified number of characters from a text or binary file into a String variable. (Analagous to the Input function in classic VB; similar to the ReadToEnd method of the StreamReader object.)

Returns a Boolean value indicating whether or not the end of a file opened for input or random access has been reached. (Analagous to the EOF function in classic VB.)

Writes data to a text file. Automatically writes the data in comma-delimited format, enclosing string fields in quotes when necessary. (Analagous to the Write statement in classic VB.) These functions will be explored in more detail in the section on Processing Text Files for Output.

Writes data to a text file.  (Analagous to the Print statement in classic VB and somewhat similar to the WriteLine method of the StreamWriter object, but with additional functionality.) These functions will be explored in more detail in the section on Processing Text Files for Output.

Closes an open file. (Analagous to the Close statement in classic VB.)

We will now explore some of these functions in more detail.

FileOpen

The FileOpen function prepares a file to be processed in the VB program.  It identifies the Windows-system file that will be used in the program and assigns the file a file number that will be used to reference that file for the remainder of the program. 

Syntax:

       FileOpen(FileNumber, FileName, Mode [, Access [, Share [, RecordLength]]])

The parameters for FileOpen are as follows:

FileNumber :                 

Required. Any valid file number. The FreeFile function can be used to obtain the next available file number.

FileName :                    

Required. String expression that specifies a valid file name — may include directory or folder, and drive.

Mode :                         

Required. Enum specifying the file mode. Possible values are:

Opens a file for output (writing). If the file does not exist, it will be created; if it does exist, records will be added to the file after the last record in the file (the previous contents of the file will not be overwritten).

Not applicable for text file processing; will be discussed in the section on binary file processing.

Opens a file for input (reading). The specified file must exist.

Opens a file for output (writing). If it does not exist, it will be created; if it does exist, its previous contents will be overwritten. 

Not applicable for text file processing; will be discussed in the section on random file processing.

Input and LineInput functions may only be used on files opened in the Input mode; Write, WriteLine, Print, and PrintLine may only be used on files opened in the Output or Append modes.

Access :                       

Optional. Enum specifying the operations permitted on the open file. Possible values are:

OpenAccess. Default

or

OpenAccess. ReadWrite

The file may be read from or written to.

The file may be read from, but not written to.

The file may be written to, but not read from.

Share :

Optional. Enum specifying the operations restricted on the open file by other processes. Possible values are:

OpenShare.Default

or

OpenShare.LockReadWrite

Other processes may neither read from nor write to the file.

Any process can read from or write to the file.

Other processes may not read from the file.

Other processes may not write to the file.

RecordLength:

Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Example:

      FileOpen(1, "C:\Program Files\EmpMaint\EMPLOYEE.TXT", OpenMode.Input)

FreeFile

Instead of hard-coding the file number, you can use the FreeFile function to supply you with a file number that is not already in use by the system.  The FreeFile function takes no arguments and returns an integer.  To use it, declare an integer variable, then assign FreeFile to it, as follows:

Dim intEmpFileNbr As Integer intEmpFileNbr = FreeFile

In the Open statement (and any other statement that refers to this file), use the integer variable rather than the hard-coded number.  For example:

      FileOpen(intEmpFileNbr, "C:\Program Files\EmpMaint\EMPLOYEE.TXT", OpenMode.Input)Input

The Input function reads a fields from a comma-delimited text file and stores the contents of that field into the specified variable.  The general format is:

· filenumber refers to the file that was opened using that number in the FileOpen function

· variable is a variable into which the "next" data field from the file will be stored

Note: In previous versions of VB and BASIC, the "Input #" statement syntax allowed you to specify a "variable list" where you could read any number of data items from the file into corresponding variables. Generally, you would use this to read one "record's worth" of data into specified variables using just one Input # statement (for example, if a record had five fields, your Input # statement would specify a list of five variables). In VB.NET, the "variable list" format is not supported for the Input function – so for the scenario with a record containing five fields, you would simply code five separate Input functions. An example is given below.

Recall the comma-delimited version of the employee file shown earlier:

image

Assume you declare the following variables in your program:

Dim strEmpName AsString Dim intDeptNbr AsInteger Dim strJobTitle AsString Dim dtmHireDate AsDate Dim sngHrlyRate AsSingle

the set of statements

Input(intEmpFileNbr, strEmpName) Input(intEmpFileNbr, intDeptNbr) Input(intEmpFileNbr, strJobTitle) Input(intEmpFileNbr, dtmHireDate) Input(intEmpFileNbr, sngHrlyRate)

would cause ANDERSON,ANDY to be stored in strEmpName, 100 to be stored in intDeptNbr, PROGRAMMER to be stored in strJobTitle, 3/4/1997 to be stored in dtmHireDate, and 25 to be stored in sngHrlyRate the first time that the statement was executed. 

The second time this set of statements is executed, BABCOCK, BILLY, 110, SYSTEMS ANALYST, 2/16/1996, and 33.5 would be stored respectively in strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate; and so on. 

As the program reads each field into its respective variable, conversion to the correct data type (Integer, Date, Single, etc.) is automatically performed.

EOF Function

The operating system automatically appends a special character, called the end-of-file marker, to the end of a sequential file.  VB can sense the presence of this end-of-file marker with the EOF function.

A programming language will generally recognize EOF at either one of two times: (1) after the last record has been read – OR – (2) at the same time that the last record has been read.  COBOL falls into the first category, VB falls into the second.

In a language that recognizes EOF after the last record in the file has been read (such as COBOL), the "input" or "read" loop is set up similar like a prompted dialog loop: with a priming readoutside the loop; all subsequent reads occur at the bottom of the loop.  The pseudocode might be written as follows:

READ (first) RECORD DO UNTIL EOF PROCESS THE RECORD READ (next) RECORD LOOP

In a language that recognizes EOF when the last record is read (such as VB), the "input" or "read" loop must be modified so that there is NO PRIMING READ and the read occurs as the FIRST statement in the body of the processing loop. The pseudocode might be written as follows:

DO UNTIL EOF READ A RECORD PROCESS THE RECORD LOOP

The syntax of the EOF function is EOF(n) where n is a number corresponding to the file number of the file from which you want to read data. n can either be a hard-coded number or an integer variable, depending on whether or not you used FreeFile with the FileOpen function.

The EOF function can be used anywhere that a conditional expression can be used; as such, it must always follow keywords such as UNTIL, WHILE, and IF.  The EOF function can also be preceded by the keyword NOT: for example, Do Until EOF(1) is equivalent to Do While Not EOF(1).

The main loop to process the employee file might look like this (note that there is no "priming" read and that the input is done at the top of the loop):

Do Until EOF(intEmpFileNbr)Input(intEmpFileNbr, strEmpName)Input(intEmpFileNbr, intDeptNbr)Input(intEmpFileNbr, strJobTitle)Input(intEmpFileNbr, dtmHireDate)Input(intEmpFileNbr, sngHrlyRate)' Processing for the record would go here – for example, load some of these ' fields into an element of an array or list box, print a line of a report, etc...LoopFileClose

When you are finished using a file in your program, you should close that file.  The FileClose function concludes input/output (I/O) to one or more files opened using the FileOpen and frees up the system resources needed to process those files.

Syntax:

where FileNumbers is a comma-delimited list of zero or more file numbers representing the files to be closed. If no file numbers are specified, all open files will be closed.

The statement

            FileClose(1)

frees the resources used by the file referenced as number 1, and also terminates the association between the Windows-system file and the file number – so at this point, if you wanted to, you could use FileOpen to open a different file using 1 as the file number.

If you have more than one file open in a program, you can close multiple files with one FileClose function by separating the file numbers with commas:

            FileClose(1, 2, 68)

The statement

            FileClose()

with no file numbers specified closes all files that are currently open.

Code for sample program #3:

The following code reads the comma-delimited file as described above, in groups of five fields at a time (one "record's worth" of data), and writes a formatted line containing the data from each record on the console. (This program produces the exact same output as the previous program exapmles.)

Module Module1  Sub Main()  Dim strFileName AsString = My.Application.Info.DirectoryPath _ & "\employee_comma.txt" Dim intEmpFileNbr AsInteger Dim strEmpName AsString Dim intDeptNbr AsInteger Dim strJobTitle AsString Dim dtmHireDate AsDate Dim sngHrlyRate AsSingle Console.WriteLine("The records in the employee_fixed.txt file are:") Console.WriteLine("") Console.WriteLine("EMPLOYEE NAME".PadRight(20) _ & Space(3) _ & "DEPT" _ & Space(3) _ & "JOB TITLE".PadRight(21) _ & Space(3) _ & "HIRE DATE " _ & Space(3) _ & "HRLY RATE") Console.WriteLine("-------------".PadRight(20) _ & Space(3) _ & "----" _ & Space(3) _ & "---------".PadRight(21) _ & Space(3) _ & "--------- " _ & Space(3) _ & "---------")  intEmpFileNbr = FreeFile()  FileOpen(intEmpFileNbr, strFileName, OpenMode.Input)  DoUntil EOF(intEmpFileNbr)  ' Read one "record's worth" of fields into their ' corresponding variables Input(intEmpFileNbr, strEmpName) Input(intEmpFileNbr, intDeptNbr) Input(intEmpFileNbr, strJobTitle) Input(intEmpFileNbr, dtmHireDate) Input(intEmpFileNbr, sngHrlyRate)  ' Output the data to the console as a formatted line ... Console.WriteLine(strEmpName.PadRight(20) _ & Space(3) _ & intDeptNbr.ToString.PadLeft(4) _ & Space(3) _ & strJobTitle.PadRight(21) _ & Space(3) _ & Format(dtmHireDate, "MM/dd/yyyy").PadRight(10) _ & Space(3) _ & Format(sngHrlyRate, "Currency").PadLeft(9)) Loop FileClose(intEmpFileNbr) Console.WriteLine("") Console.WriteLine("Press Enter to close this window.") Console.ReadLine()  EndSub End Module

A synopsis of the code follows:

Because this example uses the Microsoft.VisualBasic namespace functions only, the System.IO namespace is not required. In the Main procedure, variables to establish the filename, file number, and data fields are declared. Several lines that serve as "headings" are then written to the console. The file is then opened, and the program then commences with the main processing loop that will process data in the file in groups of five fields (one "record's worth" of data) at a time. As long as there is data remaining in the file (as tested with the EOF function), the data fields are read in with the Input function. A formatted string containing the data fields is then written to the console. When the main processing loop ends (i.e., the EOF function detects end-of-file), the file is closed, and the program ends with our standard message to close the console window.

Download the VB.NET project code for this example: Read Comma Delimited Text File Example

As in the example above, the fields within each record (line) of the file are delimited by a comma (,), and, since the employee name field itself contains a comma, it is also enclosed in quotes. The content of the file is shown below.

image

The intention of the quotes is to tell the program that is to process this file to treat the data between the quotes as a single field, thus overriding the function of the comma in that case. As shown above, we can use the "classic" method of using the retooled Input statement, but as an alternative, we can use the FileIO.TextFieldParser class, introduced in VB 2005. The FileIO.TextFieldParser class is actually a member of the Microsoft.VisualBasic namespace, so we need not import System.IO for this example.

Code for sample program #4:

The following code reads the comma-delimited file as described above and writes a formatted line containing the data from each record on the console. (This program produces the exact same output as the previous program exapmles.)

Module Module1   Sub Main()  Dim strFileName AsString = My.Application.Info.DirectoryPath _ & "\employee_comma.txt" Dim objTFParser As FileIO.TextFieldParser Dim astrTFFields() AsString  Console.WriteLine("The records in the employee_comma.txt file are:") Console.WriteLine("") Console.WriteLine("EMPLOYEE NAME".PadRight(20) _ & Space(3) _ & "DEPT" _ & Space(3) _ & "JOB TITLE".PadRight(21) _ & Space(3) _ & "HIRE DATE " _ & Space(3) _ & "HRLY RATE") Console.WriteLine("-------------".PadRight(20) _ & Space(3) _ & "----" _ & Space(3) _ & "---------".PadRight(21) _ & Space(3) _ & "--------- " _ & Space(3) _ & "---------")  objTFParser = New FileIO.TextFieldParser(strFileName) objTFParser.TextFieldType = FileIO.FieldType.Delimited objTFParser.SetDelimiters(",") objTFParser.HasFieldsEnclosedInQuotes = True  DoUntil objTFParser.EndOfData ' Read one "record's worth" of fields into the ' "astrTFFields" array ... astrTFFields = objTFParser.ReadFields  ' Output the data to the console as a formatted line ... Console.WriteLine(astrTFFields(0).PadRight(20) _ & Space(3) _ & astrTFFields(1).ToString.PadLeft(4) _ & Space(3) _ & astrTFFields(2).PadRight(21) _ & Space(3) _ & Format(CDate(astrTFFields(3)), "MM/dd/yyyy").PadRight(10) _ & Space(3) _ & Format(CSng(astrTFFields(4)), "Currency").PadLeft(9)) Loop objTFParser.Close()  Console.WriteLine("") Console.WriteLine("Press Enter to close this window.") Console.ReadLine()  EndSub End Module

A synopsis of the code follows:

Note that in addition to declaring a string variable for the filename, the variable objTFParser is declared as a FileIO.TextFieldParser object, and a string array variable astrTFFields() is declared (this array will hold the content of each record, with each element representing a field within the record). Several lines that serve as "headings" are then written to the console. The objTFParser variable is then set (with the statement objTFParser = New FileIO.TextFieldParser(strFileName)), which also serves to open the file. In the statements that follow, we also tell objTFParser that it is a delimited file, that it is delimited by commas, and that it has fields enclosed in quotes.The program then commences with the main processing loop that will process each record in the file, line by line. As long as there is data remaining in the file (as tested with the EndOfData method), a record is read from the file using the ReadFields method into the astrTFFields array variable. The ReadFields method acts in manner similar the Split method, which will cause the data from the fields to be stored in elements of the astrTFFields array. A formatted string using these field variables is then written to the console. When the main processing loop ends (i.e., EndOfData is True), the TextFieldParser is closed, and the program ends with our standard message to close the console window.

Download teh VB project code for this example: VB.NET Text Field Parser Example


View the original article here

VB.NET Strings

VB.NET has amazing support for handling strings. This includes both the native .NET methods as well as the ones in Microsoft provided Microsoft.VisualBasic namespace (which makes migrating from VB6 over to VB.NET much easier). This tutorial goes through most of the string handling functions in in both these areas and compares them to each other.

VB.NET provides a rich set of functionality for working with strings, both in terms of "native .NET" methods as well as the functions found in the Microsoft.VisualBasic namespace, which will look familiar to classic VB (pre-.NET) programmers. This article presents both the native .NET methods and the MS.VB namespace functions for string-handling. Where equivalent functionality exists between the two methodologies, the description, syntax, and examples are presented side-by-side for easy comparison.

Microsoft.VisualBasic Namespace Function

Returns an integer containing the length of the specified string.

Returns an integer containing the length of the specified string.

Len(string)

Where string is the string whose length (number of characters) is to be returned.

String.Length

Where string is the string whose length (number of characters) is to be returned.

intLen = Len("Visual Basic") ' intLen now has the value 12intLen = "Visual Basic".Length' intLen now has the value 12Getting Parts of a String (Substrings)

Microsoft.VisualBasic Namespace Function

Returns a substring containing a specified number of characters from a string.

Returns a substring containing a specified number of characters from a string.

Mid(string, start[, length])

The Mid function syntax has these parts:

string
Required. String expression from which characters are returned.

start
Required; Integer. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").

length
Optional; Integer. Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

String .Substring(start, length)

start
Required; Integer. Character position in string at which the part to be taken begins. If start is greater than or equal to the number of characters in string, Substring throws an exception.

length
Optional; Integer. Number of characters to return. If omitted all characters from the start position to the end of the string are returned.

strSubstr = Mid("Visual Basic", 3, 4)' strSubstr now contains "sual"

NOTE: The Mid function is one-based (i.e., the first position of a string is 1).

NOTE:    

Mid can also be used on the left side of an assignment statement, where you can replace a substring within a string. (When Mid is used in this manner, it is referred to as the "Mid statement" rather than the "Mid function".)

Example :

strTest = "Visual Basic"Mid(strTest, 3, 4) = "xxxx" ' strTest now contains "Vixxxx Basic"strSubstr = "Visual Basic".Substring(2, 4)' strSubstr now contains "sual"

NOTE: The Substring method is zero-based (i.e., the first position of a string is 0).

Microsoft.VisualBasic Namespace Function

Left

(NOTE: The Left function must be qualified with the Microsoft.VisualBasic namespace because Left is also a property in the Windows.Forms.Form namespace.)

Returns a substring containing a specified number of characters from the beginning (left side) of a string.

Left(string, length)

The Left function syntax has these parts:

string
Required. String expression from which the leftmost characters are returned.

length
Required; Integer. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

strSubstr = _ Microsoft.VisualBasic.Left _ ("Visual Basic", 3)' strSubstr now contains "Vis"

NOTE: The Left function is one-based (i.e., the first position of a string is 1).

' Note that the same thing could be' accomplished with MidstrSubstr = Mid("Visual Basic", 1, 3)strSubstr = "Visual Basic".Substring(0, 3)' strSubstr now contains "Vis"

REMINDER: The Substring method is zero-based (i.e., the first position of a string is 0).

Microsoft.VisualBasic Namespace Function

Right

(NOTE: The Right function must be qualified with the Microsoft.VisualBasic namespace because Right is also a property in the Windows.Forms.Form namespace.)

Returns a substring containing a specified number of characters from the end (right side) of a string.

Right(string, length)

The Right function syntax has these parts:

string
Required. String expression from which the rightmost characters are returned.

length
Required; Integer. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

strSubstr = _ Microsoft.VisualBasic.Right _ ("Visual Basic", 3)' strSubstr now contains "sic"

NOTE: The Right function is one-based (i.e., the first position of a string is 1).

' Note that the same thing could be' accomplished with Mid:strSubstr = Mid("Visual Basic", 10, 3)strSubstr = "Visual Basic".Substring(9, 3)' strSubstr now contains "sic"

REMINDER: The Substring method is zero-based (i.e., the first position of a string is 0).

Getting a Specific Character of a String with the Chars Property

To get a specific character of a string, you can use the Chars property, which will return the character found at the position specified by a number (called an index) in parentheses. The position is zero-based, so the first position of the string is 0.

Example:

Dim chrTheChar As CharDim strTest As String = "Visual Basic"chrTheChar = strTest.Chars(7)' chrTheChar now contains "B"

It is also legal syntax to omit the ".Chars" part. If omitted, the Chars method will be assumed, as in the example below:

Dim chrTheChar As CharDim strTest As String = "Visual Basic"chrTheChar = strTest(2)' chrTheChar now contains "s"

If you want to test whether or not a string begins with a certain combination of characters, you can use the StartsWith method, which returns a Boolean True or False value indicating whether or not the string being tested starts with the characters given as the argument. Therefore:

       If strTest.StartsWith("Vis") Then ...

is equivalent to:

       If strTest.Substring(0, 3) = "Vis" Then ...

or:

       If Microsoft.VisualBasic.Left(strTest, 3) = "Vis" Then ...

If you want to test whether or not a string ends with a certain combination of characters, you can use the EndsWith method, which returns a Boolean True or False value indicating whether or not the string being tested ends with the characters given as the argument. Therefore:

       If strTest.EndsWith("ic") Then ...

is equivalent to:

       If strTest.Substring(10, 2) = "ic" Then ...

or:

       If Microsoft.VisualBasic.Right(strTest, 2) = "ic" Then ... Finding One String Within Another

Microsoft.VisualBasic Namespace Function

Returns an integer specifying the position of one string within another. The search starts either at the first character position or at the position specified by the start argument, and proceeds forward toward the end of the string (stopping when either string2 is found or when the end of the string1 is reached). If the string is not found, 0 is returned.

Returns an integer specifying the position of one string within another. The search starts either at the first character position or at the position specified by the startindex argument, and proceeds forward toward the end of the string (stopping when either string is found or when the end of thestring being searchedis reached). If the string is not found, -1 is returned. IndexOf performs a case-sensitive search.

InStr

([start,] string1, string2 [, compare])

The InStr function syntax has these parts:

start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. The start argument is required if compare is specified.

string1
Required. String expression being searched.

string2
Required. String expression sought.

compare
Optional; numeric. A value of 0 (the default) specifies a binary (case-sensitive) search.  A value of 1 specifies a textual (case-insensitive) search.

NOTE:  The CompareMethod enumeration can be specified for the compare argument: for 0 (case-sensitive), CompareMethod.Binary is used; for 1 (case-insensitive), CompareMethod.Text is used. Alternatively, the older "vb" constants vbBinaryCompare and vbTextCompare can be used for 0 and 1 respectively.

NOTE:  If the optional compare argument is specified, then the start argument must also be specified.

String .IndexOf(string [, startindex])

string
String expression sought.

startindex
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position.

intPos = Instr("Visual Basic", "a")' intPos now has the value 5' (search started at position 1 ' by default and is case-sensitive ' by default) intPos = Instr(6, "Visual Basic", "a")' intPos now has the value 9' (search started at position 6' and is case-sensitive by default) intPos = Instr("Visual Basic", "A")' intPos now has the value 0' (case-sensitive search was performed' by default) intPos = Instr(1, "Visual Basic", _"A", 1)- or –intPos = Instr(1, "Visual Basic", _"A", CompareMethod.Text) ' intPos now has the value 5' (search started at position 1 and is' case-insensitive)

NOTE: The Instr function is one-based (i.e., the first position of a string is 1).

intPos = "Visual Basic".IndexOf("a")' intPos now has the value 4 intPos = "Visual Basic".IndexOf("a", 6)' intPos now has the value 8 intPos = "Visual Basic".IndexOf("A")' intPos now has the value -1

NOTE: The IndexOf method is zero-based (i.e., the first position of a string is 0).

Microsoft.VisualBasic Namespace Function

Returns an integer specifying the position of one string within another. The search starts either at the last character position or at the position specified by the start argument, and proceeds backward toward the beginning of the string (stopping when either string2 is found or when the beginning of the string1 is reached). If the string is not found, 0 is returned.

Returns an integer specifying the position of one string within another. The search starts either at the last character position or at the position specified by the startindex argument, and proceeds backward toward the beginning of the string (stopping when either string is found or when the beginning of the string being searched is reached). If the string is not found, -1 is returned. LastIndexOf performs a case-sensitive search.

InStrRev

(string1, string2[, start, [, compare]])

The InStrRev function syntax has these parts:

string1
Required. String expression being searched.

string2
Required. String expression sought.

start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the last character position.

compare
Optional; numeric. A value of 0 (the default) specifies a binary (case-sensitive) search.  A value of 1 specifies a textual (case-insensitive) search.

NOTE:  The CompareMethod enumeration can be specified for the compare argument: for 0 (case-sensitive), CompareMethod.Binary is used; for 1 (case-insensitive), CompareMethod.Text is used. Alternatively, the older "vb" constants vbBinaryCompare and vbTextCompare can be used for 0 and 1 respectively.

String .LastIndexOf(string [, startindex])

string
String expression sought.

startindex
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the last character position.

intPos = InstrRev("Visual Basic", "a")' intPos now has the value 9' (search started at last position' by default and is case-sensitive ' by default) intPos = InstrRev("Visual Basic", _ "a", 6)' intPos now has the value 5' (search started at position 6' and is case-sensitive by default) intPos = InstrRev("Visual Basic", "A")' intPos now has the value 0' (case-sensitive search was performed' by default) lngPos = InstrRev("Visual Basic", _ "A", , 1) ' intPos now has the value 9' (search started at last position' and is case-insensitive)' Note that this example has a ' placeholder for the optional' start argument.

NOTE: The InstrRev function is one-based (i.e., the first position of a string is 1).

intPos = "Visual Basic".LastIndexOf("a")' intPos now has the value 8 intPos = _ "Visual Basic".LastIndexOf("a", 6)' intPos now has the value 4 intPos = "Visual Basic".LastIndexOf("A")' intPos now has the value -1

NOTE: The LastIndexOf method is zero-based (i.e., the first position of a string is 0).

If you want to test whether or not one string is contained within another, you can use the Contains method, which returns a Boolean True or False value indicating whether or not the string being tested contains the characters given as the argument. Therefore:

       If strTest.Contains("asi") Then ...

is equivalent to:

       If strTest.IndexOf("asi") <> -1 Then ...

or:

       If Instr(strTest, "asi") > 0 Then ... Replacing Text Within a String

Microsoft.VisualBasic Namespace Function

Returns a string in which a specified substring has been replaced with another substring a specified number of times.

Returns a string in which all occurrences of a specified substring has been replaced with another substring.

Replace (expression, find, replacewith[, start[, count[, compare]]])

The Replace function syntax has these parts:

expression
Required. String expression containing substring to replace.

find                 
Required. Substring being searched for.

replacewith      
Required. Replacement substring.

start    
Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed.

count
Optional. Number of substring substitutions to perform. If omitted, the default value is –1, which means make all possible substitutions.

compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. (0 = case sensitive, 1 = case-insensitive)

NOTE:  The CompareMethod enumeration can be specified for the compare argument: for 0 (case-sensitive), CompareMethod.Binary is used; for 1 (case-insensitive), CompareMethod.Text is used. Alternatively, the older "vb" constants vbBinaryCompare and vbTextCompare can be used for 0 and 1 respectively.

String .Replace(oldstring, newstring)

oldstring
Required. Substring being searched for.

newstring
Required. Replacement substring.

strNewDate = _ Replace("08/31/2001", "/", "-")' strNewDate now contains "08-31-2001"strNewDate = _ "08/31/2001".Replace("/", "-")' strNewDate now contains "08-31-2001"Microsoft.VisualBasic Namespace Function

Converts all lowercase letters in a string to uppercase. Any existing uppercase letters and non-alpha characters remain unchanged.

Converts all lowercase letters in a string to uppercase. Any existing uppercase letters and non-alpha characters remain unchanged.

strNew = UCase("Visual Basic")' strNew now contains "VISUAL BASIC"strNew = "Visual Basic".ToUpper' strNew now contains "VISUAL BASIC"Microsoft.VisualBasic Namespace Function

Converts all uppercase letters in a string to lowercase. Any existing lowercase letters and non-alpha characters remain unchanged.

Converts all uppercase letters in a string to lowercase. Any existing lowercase letters and non-alpha characters remain unchanged.

strNew = LCase("Visual Basic")' strNew now contains "visual basic"strNew = "Visual Basic".ToLower' strNew now contains "visual basic"Microsoft.VisualBasic Namespace Function

Removes leading blank spaces from a string.

Removes leading blank spaces from a string.

strTest = LTrim(" Visual Basic ")' strTest now contains "Visual Basic "strTest = " Visual Basic ".TrimStart' strTest now contains "Visual Basic "Microsoft.VisualBasic Namespace Function

Removes trailing blank spaces from a string.

Removes trailing blank spaces from a string.

strTest = RTrim(" Visual Basic ")' strTest now contains " Visual Basic"strTest = " Visual Basic ".TrimEnd' strTest now contains " Visual Basic"Microsoft.VisualBasic

Namespace Function

Removes both leading and trailing blank spaces from a string.

Removes both leading and trailing blank spaces from a string.

strTest = Trim(" Visual Basic ")' strTest now contains "Visual Basic"strTest = " Visual Basic ".Trim' strTest now contains "Visual Basic"More VB.NET String-Handling Methods

Concatenates two or more strings together. This can be used as an alternative to the + or & operators.

String.Concat(string1, string2, ... stringn)

The following three statements are all equivalent:

strTest = String.Concat("Hello ", "World")strTest = "Hello " & "World"strTest = "Hello " + "World"

Inserts characters into a string

String .Insert(startindex, value)

startindex        
Required. The (zero-based) position at which to insert characters.

value               
Required. The string of characters to insert.

strTest = "The time now."strTest = strTest.Insert(9, "is ")' strTest now contains "The time is now."

Removes characters from a string

String .Remove(startindex [, count])

startindex        
Required. The (zero-based) position at which to delete characters.

count              
Optional. The number of characters to delete. If omitted, all characters from startindex to the end of the string will be deleted.

strTest = "Two hundred dollars."strTest = strTest.Remove(4, 8)' strTest now contains "Two dollars." strTest = strTest.Remove(3)' strTest now contains "Two"

Returns a string that is right-aligned and padded on the left with spaces (or other specified character) so that the length of the string is the specified width.

String .PadLeft(totalWidth [, paddingChar])

totalWidth        
Required. The total number of characters to be contained in the resulting string.

paddingChar    
Optional. The character to pad the string with. If omitted, a blank space will be used.

strName = "John Doe"strNewName = strName.PadLeft(15)' strNewName now contains " John Doe" strNewName = strName.PadLeft(15, "*")' strNewName now contains "*******John Doe"

Returns a string that is left-aligned and padded on the right with spaces (or other specified character) so that the length of the string is the specified width.

String .PadRight(totalWidth [, paddingChar])

totalWidth        
Required. The total number of characters to be contained in the resulting string.

paddingChar    
Optional. The character to pad the string with. If omitted, a blank space will be used.

strName = "John Doe"strNewName = strName.PadRight(15)' strNewName now contains "John Doe " strNewName = strName.PadRight(15, "*")' strNewName now contains "John Doe*******"String Object

(NOTE: This can be used as an equivalent to the String function found in pre-.NET versions of Visual Basic)

Can be used to return a string containing a repeating character string of the length specified.

New String(character, count)

character
The character to be repeated.

count              
The number of characters to pad the string with.

strTest = New String("*", 5)' strTest now contains "*****"More Microsoft.VisualBasic Namespace String-Handling Functions

Returns a string in which the character order of a specified string is reversed.

strTest = StrReverse ("Visual Basic") ' strTest now contains "cisaB lausiV"

Returns a string containing the specified number of blank spaces.

Space(number)

Where number is the number of blank spaces desired.

strTest = Space(5)' strTest now contains " "

Returns an Integer representing the ASCII character code corresponding to the first letter in a string.

intCode = Asc("*") ' intCode now has the value 42intCode = Asc("ABC") ' intCode now has the value 65

Returns a string containing the character associated with the specified ASCII character code.

Chr(charcode)

Where charcode is a number from 0 to 255 that identifies the character.

strChar = Chr(65)' strChar now contains "A""Try It" Example

To demonstrate the built-in string functions, set up a "Try It" console project, and place the following code in the main method:

Sub Main()Dim strTest AsStringConsole.Write("Please enter a string: ")strTest = Console.ReadLine()Console.WriteLine("Using Len and Length: <" _ & CStr(Len(strTest)) & "><" & CStr(strTest.Length) & ">")Console.WriteLine("Using Mid, Left, Right, and Substring: <" _ & Mid(strTest, 3, 4) _ & "><" & Microsoft.VisualBasic.Left(strTest, 3) _ & "><" & Microsoft.VisualBasic.Right(strTest, 2) _ & "><" & strTest.Substring(2, 4) & ">")Console.WriteLine("Using Chars: <" & strTest.Chars(0) & "><" & strTest(7) & ">")Console.WriteLine("Using StartsWith and EndsWith: <" _ & CStr(strTest.StartsWith(" Vis")) _ & "><" & CStr(strTest.EndsWith("ic")) & ">")Console.WriteLine("Using Instr, IndexOf, InstrRev, and LastIndexOf: <" _ & CStr(InStr(strTest, "a")) _ & "><" & CStr(strTest.IndexOf("a")) _ & "><" & CStr(InStrRev(strTest, "a")) _ & "><" & CStr(strTest.LastIndexOf("a")) & ">")Console.WriteLine("Using Contains: <" & CStr(strTest.Contains("asi")) & ">")Console.WriteLine("Using the Replace function and Replace method: <" _ & Replace(strTest, "a", "*") & "><" & strTest.Replace("a", "*") & ">")Console.WriteLine("Using UCase and ToUpper: <" _ & UCase(strTest) & "><" & strTest.ToUpper & ">")Console.WriteLine("Using LCase, and ToLower: <" _ & LCase(strTest) & "><" & strTest.ToLower & ">")Console.WriteLine("Using LTrim and TrimStart: <" _ & LTrim(strTest) & "><" & strTest.TrimStart & ">")Console.WriteLine("Using RTrim and TrimEnd: <" _ & RTrim(strTest) & "><" & strTest.TrimEnd & ">")Console.WriteLine("Using the Trim function and Trim method: <" _ & Trim(strTest) & "><" & strTest.Trim & ">")Console.WriteLine("Using Concat: <" & String.Concat(strTest, "-", strTest) & ">")Console.WriteLine("Using Insert: <" & strTest.Insert(3, "*****") & ">")Console.WriteLine("Using Remove: <" & strTest.Remove(3, 2) & ">")Console.WriteLine("Using PadLeft and PadRight: <" _ & strTest.PadLeft(20, "*") & "><" & strTest.PadRight(20) & ">")Console.WriteLine("Using String, Space, and Chr: <" _ & NewString("*", 3) & Space(2) & Trim(strTest) & Space(2) _ & NewString(Chr(42), 3) & ">")Console.WriteLine("Using StrReverse: <" & StrReverse(strTest) & ">")Console.WriteLine("Using Asc: <" & CStr(Asc(strTest)) & ">")Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

Run the project and enter a string of your choice.

Some tips on what to enter:

To see the effects of UCase, LCase, ToUpper, and ToLower, enter a mixed case string. To see the effects of Instr, InstrRev, IndexOf, and LastIndexOf, enter a string with at least two "a"s in it. To see the effects of LTrim, RTrim, TrimStart, TrimEnd, and Trim, enter a string with leading and/or trailing spaces. To see the effect of Replace, enter a string with at least one "a" in it.

You can also modify the code and run the project to see if you get the results you expect.

The screen shot below shows a run of the project using the code above where the string Visual Basic was input:

image

Download the VB Project code for this example: VB.NET String Function Example

This article was original written by The VB Programmer.


View the original article here

From VB6 to VB.NET with the Microsoft.VisualBasic Namespace

In addition to "native .NET" methods for handling strings, dates, file input/output and the like, the .NET framework includes the Microsoft.VisualBasic namespace, which contains functions that will look very familiar to classic VB (pre-.NET) programmers. In nearly all cases, the MS.VB namespace functions behave identically to their pre-.NET (i.e., VB6) counterparts. Whether or not the Microsoft.VisualBasic namespace functions should be used is the subject of some debate.

"Purists" will argue that only the native .NET methods should be used because they are common across all .NET languages (C# for example), that the MS.VB namespace functions may not be supported in future versions (although Microsoft insiders have actually indicated the opposite), and for more subjective reasons (such as a desire to make a clean break with the past, or the attitude that these "legacy" functions are simply not the ".NET way").

On the other hand, it is no less efficient to use the MS.VB namespace functions (and in many cases they are more efficient), in some cases they provide functionality not easily replicated with native .NET methods, and from a productivity standpoint, they provide a comfort zone to those coming to .NET from a VB6 or VBA background.

Please note that the Microsoft.VisualBasic namespace should not be confused with the Microsoft.VisualBasic.Compatibility namespace, which is used primarily by upgrade tools and should NOT be used for development.

In the other articles on this site, where equivalent functionality exists in both the native .NET methods and the Microsoft.VisualBasic namespace, both methodologies will be presented without bias. Where applicable, the descriptions, syntax, and examples will be presented side-by-side for easy comparison.

The chart below provides a partial list of the items that will be covered in the articles to follow.

Microsoft.VisualBasic Namespace Function

New String (equivalent to the pre-.NET "String" function to create a string of repeating characters)

AddDays, AddMonths, AddYears, AddHours, AddMinutes, AddSeconds

TimeSpan variable = Date1 – Date2

DatePart, Month(datevar), Day(datevar), Year(datevar), Hour(datevar), Minute(datevar), Second(datevar)

datevar. Month, datevar.Day, datevar.Year, datevar.Hour, datevar.Minute, datevar.Second

This article was original written by The VB Programmer.


View the original article here

Tuesday, February 28, 2012

From VB6 to VB.NET with the Microsoft.VisualBasic Namespace

In addition to "native .NET" methods for handling strings, dates, file input/output and the like, the .NET framework includes the Microsoft.VisualBasic namespace, which contains functions that will look very familiar to classic VB (pre-.NET) programmers. In nearly all cases, the MS.VB namespace functions behave identically to their pre-.NET (i.e., VB6) counterparts. Whether or not the Microsoft.VisualBasic namespace functions should be used is the subject of some debate.

"Purists" will argue that only the native .NET methods should be used because they are common across all .NET languages (C# for example), that the MS.VB namespace functions may not be supported in future versions (although Microsoft insiders have actually indicated the opposite), and for more subjective reasons (such as a desire to make a clean break with the past, or the attitude that these "legacy" functions are simply not the ".NET way").

On the other hand, it is no less efficient to use the MS.VB namespace functions (and in many cases they are more efficient), in some cases they provide functionality not easily replicated with native .NET methods, and from a productivity standpoint, they provide a comfort zone to those coming to .NET from a VB6 or VBA background.

Please note that the Microsoft.VisualBasic namespace should not be confused with the Microsoft.VisualBasic.Compatibility namespace, which is used primarily by upgrade tools and should NOT be used for development.

In the other articles on this site, where equivalent functionality exists in both the native .NET methods and the Microsoft.VisualBasic namespace, both methodologies will be presented without bias. Where applicable, the descriptions, syntax, and examples will be presented side-by-side for easy comparison.

The chart below provides a partial list of the items that will be covered in the articles to follow.

Microsoft.VisualBasic Namespace Function

New String (equivalent to the pre-.NET "String" function to create a string of repeating characters)

AddDays, AddMonths, AddYears, AddHours, AddMinutes, AddSeconds

TimeSpan variable = Date1 – Date2

DatePart, Month(datevar), Day(datevar), Year(datevar), Hour(datevar), Minute(datevar), Second(datevar)

datevar. Month, datevar.Day, datevar.Year, datevar.Hour, datevar.Minute, datevar.Second

This article was original written by The VB Programmer.


View the original article here

How to connect DB

How to connect DB

Simple Windows API Example

When developing Windows applications one of the most useful things a person can know is how to interact with the Win32 API. By understanding these functions and hooks that Microsoft provides we are able to unleash a vast array of extra capabilities that are not yet built into the VB.NET libraries. This tutorial walks through a simple example of how to call into the Windows API.

The Windows API is a set of code libraries (DLL files) containing numerous functions for working with all aspects of Windows (graphics, the file system, fonts, low-level memory access, etc.). These function libraries are available to programmers coding with any Windows development system (VB, C++, Delphi, etc.).

While using the API is often treated as an "advanced" programming topic (and to be sure, using the API allows you to delve as deep into the depths of Windows programming as you desire), the coding to actually set up and use an API function is relatively straightforward. The basic steps are:

Declare the API sub or function with the Declare statement. The Declare statement must be coded in the general declarations section of a form or module, and can be declared with either Public or Private scope (Private only in forms). If declared as Public, any form or module in your VB.NET application can use the function; if Private, only the form or module in which it is declared can use the function. Declare any variables and constants necessary to be used as parameters with the sub or function. Call the sub or function as you would any other sub or function. (Be advised that there are some differences between calling API functions versus regular VB.NET subs and functions.)

To find the declarations and documentation necessary to use any of the 1000+ Windows API functions available, you can consult any of the numerous API Help websites. Google is of course best for searching.

Sample Program

We will now build a simple program that demonstrates the use of API functions. We will call upon the "GetComputerName" function to access the name of your computer and display it in the console winodw.

Note: On Windows XP, the name of the computer can be found by right-clicking on the My Computer icon and choosing Properties, which then displays the System Properties screen shown below. The second tab, Computer Name, shows your computer name. In this case, the name of the computer is “toshiba-user” (shown circled in red below).

image

Following is the code for the sample console application to display the computer name:

Module Module1 Private Declare Function GetComputerName _Lib "kernel32.dll" Alias "GetComputerNameA" _ ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger Sub Main() Dim strBuffer AsString Dim intCharCount AsInteger Dim intRetVal AsInteger Const MAX_COMPUTERNAME_LENGTH AsInteger = 31 Dim strMessage AsString intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount) If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf Console.WriteLine(strMessage) Console.WriteLine("") Console.WriteLine("(Press Enter to close this window.)") Console.ReadLine() EndSubEnd Module

A screen-shot of the run is shown below:

image

We can analyze the code as follows. First, an explanation of the Declare statement. The Declare statement has the following general syntax:

[Public | Private] Declare Function Name Lib LibraryName [Alias AliasName] ([parameter list]) As datatype

- or -

[Public | Private] Declare Sub Name Lib LibraryName [Alias AliasName] ([parameter list])

As discussed above, the Public or Private keyword establishes the scope of the function as it will be used in your program.

As in normal VB Subs and Functions, use the Function keyword (and the corresponding As datatype clause at the end of the declaration) if the API function returns a value (in most cases, the "Function" form will be used, and the return value (datatype) will be Integer). In other cases, where the API function does not return a value, use the Sub keyword and leave off the As datatype clause.

Name specifies the name of the function as it will be used in the VB program. When the internal name of the function within the library (DLL file) is different, use the Alias clause to specify the actual internal name within the DLL.

LibraryName specifies which DLL the function can be found in.

AliasName specifies the actual internal name of the function within the Windows DLL file. The Alias clause needs to be used if the name used for Name is different. The Alias clause is useful when an internal name conflicts with a keyword (but can be used if you simply want to use a different name to call the function).

Parameter list is the comma-separated list of arguments that the function expects.

As datatype specifies the data type returned by the function. In most cases, this is a 32-bit integer specified in VB.NET as Integer. (Note: In previous versions of VB, the Integer data type was a 16-bit integer and the Long was a 32-bit integer. Thus, the return value for API functions was typically specified as Long when declaring APIs in the previous VB versions. In VB.NET, the Integer data type is now a 32-bit integer and the Long is a 64-bit integer, so we must use Integer data type to specify the return value for API functions.)

In this example, our declaration looks like this:

Private Declare Function GetComputerName Lib _"kernel32.dll" Alias "GetComputerNameA" _(ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger

This tells the system we are looking for the GetComputerName function located in the kernel32.dll Windows system file. (The Alias clause indicates that the actual name of the function in the dll is GetComputerNameA, however, declaring the function as above, we can refer to the function as GetComputerName in our VB code.)

The arguments to this particular function are lpBuffer, which is a string that will store the computer name, and nSize which is a number (integer) that will store the number of characters contained in the computer name. (Technically, the lpBuffer argument is a “null-terminated string”, which is a string in which the trailing character(s) are the null character (ASCII code 0). The characters up to but not including the first null character represents the value of the string.)

The As Integer specification at the end of our declaration indicates that the function will be returning a Integer value. In the case of many API functions, a 32-bit Integer value will be returned to indicate the success or failure of the call.

The crux of the processing occurs in these three lines. We are setting the variable intCharCount to the value of the constant MAX_COMPUTER_LENGTH, which is set to 31. The next statement pads the variable strBuffer with 32 null characters. The actual call to the API function follows, which causes the computer name to be stored in strBuffer (in our case the result will be the string “TOSHIBA-USER” followed by 20 null characters). This is because the string “TOSHIBA-USER” contains 12 characters, and since the total length of the string is 32 characters, 20 null characters will trail at the end of the string. The function will also store the value 12 in the variable intCharCount, representing the number of characters in the name that was retrieved. The result of the function (the return value) is stored in the variable intRetVal. If the result is non-zero, the function succeeded; if zero, the function failed.

intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount)

The code that follows tests the return value. If the return value is non-zero, then the call was successful, and a message containing the computer’s name is stored in the variable strMessage (the Substring method is applied to the strBuffer variable to grab its 12 leftmost characters). Otherwise, we set strMessage to indicate that the function failed. In any case, the message is then displayed on the console.

If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf  Console.WriteLine(strMessage)

Download the VB Project code for the example above: VB.NET API Example

NOTE : We can use the API functions in VB.NET using the steps covered in this article. However, it must be noted that most of the functionality of Windows API has been encapsulated in Object Oriented Classes of .NET framework and many more will be added to this list of classes and functions. Therefore, it is recommend that before using an API, we must check if the similar functionality is available in .NET classes.

This article was original written by The VB Programmer.


View the original article here

VB.NET Input Box

An often used feature in classic Visual Basic is the InputBox function. It provides an easy way to prompt the user for simple text input. VB.NET carries this handy function forward for all to use. Although you probably won’t use this any time you need to request a large or amount of data or in other complex scenarios, it does provide a simple and effective way to get input in your Visual Basic.NET apps.

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a string containing the contents of the text box.

Usage :

stringvariable = InputBox(prompt[, title] [, default] [, xpos] [, ypos])

The arguments to the InputBox function are described below:

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.

Both optional. Numeric expressions that specify custom positioning of the box on screen (by default, the box is displayed in the center of the screen, which is usually desired).

Remarks

If the user clicks OK or presses ENTER , the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

Sample Program

The sample program uses a form with two buttons and a label, laid out as shown below:

image

The properties set for these controls are as follows:

(First Button):

Name: cmdGetInputText: Get Input

(Label):

Name: lblInfoAutoSize: FalseBackColor: KhakiBorderStyle: Fixed SingleText: (clear)

(Second Button):

The code for the program is shown below:

Public Class Form1 PrivateSub cmdGetInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetInput.Click Dim strUserName AsString  strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")  If strUserName = ""Then ' user cancelled the InputBox, so clear the label lblInfo.Text = "" Else lblInfo.Text = "User Name: " & strUserName EndIf EndSub  PrivateSub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() EndSubEnd Class

When the program is run and you click the "Get Input" button, the following input box is displayed. Note the content of the box based upon the values used as the arguments for the InputBox function:

        strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")

image

Enter your name in the text entry portion of the box (in this example, the name John is entered):

image

After you click OK, the text "User Name: " concatenated with the name you entered will be displayed in the label:

image

You can download the example code for this tutorial here: InputBox VB.NET Example

This article was original written by The VB Programmer.


View the original article here