Showing posts with label VBNET. Show all posts
Showing posts with label VBNET. Show all posts

Sunday, March 18, 2012

Find duplicate files using VB.Net

When you are receiving files from different server hosting but the content is same, there is a possibility of having a different filename for the same content. Hence finding a duplicate file just by file name may not be sufficient. To compare by file data, there are several ways.

To find duplicate files even after renamed, the content/data has to be compared after the content of files fetched. Once the file content is in data format, the data can be encoded with MD5 hash algorithm. The string result after hash can be used for comparing. MD5 is a widely used cryptographic hash function with a 128-bit hash value, and is also commonly used to check the integrity of files

.NET Framework has very rich support for encryptWing and decrypting. Computing hashes and encrypting data using a variety of algorithms is very easy. Use the ComputeHash() method to compute the MD5 Hash.

For the MD5 to work we should give which encoding it should follow, basically we are using ASCIIEncoding. This same function can be used in a recursive call to check all the duplicates. Once all the files in the directory are scanned and compared it is much easier to delete the duplicate files found.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (CompareFiles("D:\FirstFile.txt", "D:\FirstFile1.txt")) Then
MsgBox("duplicate")
Else
MsgBox("diff")
End If
End Sub
Public Function CompareFiles(ByVal FirstFile As String, _
ByVal SecondFile As String) As Boolean
Return ReadFile(FirstFile) = ReadFile(SecondFile)
End Function
Private Function ReadFile(ByVal Path As String) As String
Dim ReadFileStream As FileStream
Dim FileEncoding As New System.Text.ASCIIEncoding()
Dim FileReader As StreamReader
Dim HashData As New MD5CryptoServiceProvider()
ReadFileStream = New FileStream(Path, FileMode.Open)
FileReader = New StreamReader(ReadFileStream)
Dim FileBytes = FileEncoding.GetBytes(FileReader.ReadToEnd)
Dim FetchedContent = FileEncoding.GetString(HashData.ComputeHash(FileBytes))
FileReader.Close()
ReadFileStream.Close()
Return FetchedContent
End Function

View the original article here

Friday, March 16, 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

Thursday, March 15, 2012

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

Wednesday, March 14, 2012

VB.Net kill process by name

 .Net made it very easy for handling processes. It is much easier to close the applications using Process.Kill(). Processes can be iterated using the ‘for each’ loop. The process object taken from enumeration has enough methods and properties to deal with processes.

To get the list of instances running with the current applications name, we can use the Process.GetProcessesByName(“ProcessName”). This method returns collection of processes with the name “ProcessName”.  Thereafter accessing each process is easy with a ‘for each’ loop.

I had a requirement to ensure that, current process is the only running process. The rest of the other instances of the processes have to be closed. Using the GetProcessesByName method we can get the list of current instances. While iterating thro the collection, we can identify the current process by the ID property. We can get the current running process by Process.GetCurrentProcess(). Now it is very easy to kill other process than the current one.

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
For Each RunningProcess In Process.GetProcessesByName("Notepad")
RunningProcess.Kill()
Next
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
For Each RunningProcess In Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If (Not RunningProcess.Id = Process.GetCurrentProcess().Id) Then
RunningProcess.Kill()
End If
Next
End Sub
End Class

View the original article here

VB.net ComboBox AutoComplete


This article is written by Pon Saravanan  on 21-Jan-11 Last modified on :08-Feb-11

ComboBox control is similar to ListBox control, in which you can select one item from a list of items. But it takes less space on screen and it allows you to locate an item by setting value to the ComboBox control’s text property. In simple word, it is an expandable(collapse/expand) ListBox control. Here we are going to see the AutoCompleteMode property in ComboBox control. This property automatically matches the input string given on runtime (starts with match) of all strings in the source database column. Based on that it will display the matched string in ComboBox. This property is very useful for frequently searching strings. Such as URLs, file name, customer name, or any command that is frequently used. This property go well when there is no duplication in source data. If there is duplication occurs in source data then the AutoCompleteMode property omits the duplication and display only once. There is an easy way to fetch data from the SQL server, first select the “Add New Item” from Project menu. In which, select “LINQ to SQL Classes”, name it as Northwind.dbml and press Add button. Now you get the new Northwind.dbml designer on screen. Now drag the Customer table from server explorer window to Northwind.dbml. Now you can fetch the source data from SQL server by using the following code

ComboBox1.DataSource = (New NorthwindDataContext).Customers.Where(Function(Cust)
Cust.ContactName.Contains(comboBox1.SelectedText))

Pickup a ComboBox control from the toolbox and place it in your form1.vb[Design]. Now set the “DropDownStyle” property value as DropDown. To execute AutoCompleteMode property, The AutoCompleteModeProperty and AutoCompleteSource property must be used together. First you should set the AutoCompleteMode property value as Suggest and set AutoCompleteCustomSource property value as ListItems. If the value of AutoCompleteCustomSource property is null, then the prefix of the source data that gets matched with the input string will not get listed below the ComboBox .
The following code is used to set both the properties.

ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
ComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems

Imports System.Linq
Imports System.Collections.Generic
Imports System.Data.SqlClient
Public Class Form1
Private RowCount As Integer
Private Function GetData() As IEnumerable
Dim Datacontext As New NorthwindDataContext
Dim Filtered = Datacontext.Customers.Where(Function(Cust) _
Cust.ContactName.Contains(ComboBox1.SelectedText))
Return Filtered
End Function
Private Sub LoadCustomers()
ComboBox1.DisplayMember = "ContactName"
ComboBox1.DataSource = GetData()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
ComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
LoadCustomers()
End Sub
End Class

View the original article here

Tuesday, March 13, 2012

Vb.Net Draw In Picturebox

‘System.Drawing’ can be one of the fun working libraries for working on interesting tasks like imaging. This is loaded with a lot of features that can make the drawing and imaging activities much easier.

I usually prefer to work with bitmap when I am working on the imaging. The reason behind is, it has a lot of properties and methods to work with.  We can easily save, change the pixel, and retrieve the pixel.

Just like drawing the lines, pixels, circles on an image, it is very easy to write a text on the image using graphic object’s DrawString() method. This graphic object has to be based on the image where we are going to write to. So use the FromImage function of the Graphics to get the graphics object of the image.

Graphics object can be used to format the image, text. So use the properly suited overloaded method to handle the required formats using font, brush, location. I demonstrated how to use brush, and font in a very simple manner. Though you can do bold, italics, colorful, I will leave it to you to discover.

_
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.

View the original article here

GridView Sorting Vb.Net

GridView sorting is very easy to enable. But only few functionalities are available out of the box, so still a few things should be configured and coded. The first thing to enable sorting is AllowSorting = true. Then SortExpression has to be specified. Normally column name has to be given for the SortExpression. With this the GridView  view will be able to sort based on the SortExpression given.

After configuring the above when you click on the sort link in the header of the respective column, an exception will be thrown that the Sorting event is not handled. In this event we need to sort the data using a DataView. DataView has a Sort which we can use to pass the expression.

Actually when a GridView is sorted in either ascending or descending order the next expected has to be opposite for the first sorting. If the first sorting is ascending then the second sorting has to be descending.

DataView can be obtained from Data Table’s DefaultView. Data View’s Sort property can sort the data based on the given ascending or descending suffix. After this rebind the GridView  to sort.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>



Untitled Page



ID="GridView1" ShowFooter="true" >








Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private Property SortDirection() As String
Get
If (ViewState("SortDirection") Is Nothing) Then ViewState("SortDirection") = String.Empty
Return ViewState("SortDirection").ToString()
End Get
Set(ByVal value As String)
ViewState("SortDirection") = value
End Set
End Property
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
If (Not IsPostBack) Then
GridView1.DataSource = GetSortableData(String.Empty) 'System.Drawing.FontFamily.Families

View the original article here

Monday, March 12, 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

Friday, March 9, 2012

VB jobs offer for VB6 and VB.net Programmers!

Paraminfotech is offering VB6 and VB.net programming jobs to potential candidates, the following is the email they sent to us:

“Dear Friends,

We require following candidates :

VB6 cum VB.net Programmers : Candidate must be having minimum 2 years and maximum 4 years of programming experience in VB6 and minimum 1 year experience in VB.net.

Send your resumes to resumes@paraminfotech.com with your current & expected salary.

Thanks & Regards,

Param Infotech Income tax, Ahmedabad.

My name is Liew Voon Kiong. I hold a Bachelor Degree in Mathematics, a Master Degree in Management and a Doctoral Degree in Business Administration. I obtained the DBA degree from University of South Australia.I have been involved in programming for more than 15 years. I created this popular online Visual Basic Tutorial in 1996 and since then the web site has attracted millions of visitors .It is the top ranked Visual Basic tutorial website in many search engines including Google. I have also written a few Visual Basic related books. One of the books, Visual Basic 6 Made Easy was published by BookSurge LLC, an Amazon.com publisher. The rest are ebooks. Learn more about the author at helium.com

View the original article here

Monday, March 5, 2012

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

Sunday, March 4, 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

Friday, March 2, 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

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

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