how to remove a specific string from a label - vb.net

I'm trying to remove a specific string out of a label. The label is suppose to print an error message while the input is invalid, as soon as the user changes the textbox input to a number, the error message should disappear for that specific input.
Here is what I tried so far but the "-=" did not work as I expected.
Sub errorOutput(toggleError As Boolean, courseNumber As Integer)
Dim err(6) As String
err(courseNumber) = "please ensure that what you input in Course " + courseNumber.ToString + " is a number between 0 and 100"
If toggleError = True Then
lblError.Text += err(courseNumber)
Else
lblError.Text -= err(courseNumber)
End If
End Sub

When applied to two Strings, the + operator does concatenation. It appends the string on the right-hand side of the operator to the string on the left-hand side of the operator.
(Technically, it creates a new String object that represents the concatenation of the left-hand and right-hand strings, since strings are immutable in .NET, but that's a technical detail you probably don't care about.)
The += operator is referred to as a compound assignment operator. It merges together an operator that modifies the value (in this case, the +) with the assignment operator (=), so that you can get both at once.
Okay, so you know how this works already. You're using +=, and you can append two strings, and everything is good.
So, by way of analogy, you try -=. Wait…what should happen? What does it mean to subtract two strings? Subtracting two numbers, well, that makes perfect sense. But how do you subtract a string?
It's not obvious what operation would be performed, so the subtraction operator doesn't do anything for String objects. It hasn't been defined, because its semantics are not clear. Only concatenation is defined, using the + operator (and also the & operator).
If you need to "remove" a portion of a string, you will have to write a bit more code, using one or more of the methods provided by the String class to spell out exactly what operation you want to happen. For example, you could use the String.Replace method to replace all occurrences of one string with another string (or even an empty string):
Dim message As String = "My favorite color is yellow."
message = message.Replace("yellow", "blue")
But in this case, you probably just want to clear the Label control first, and then only add in the error messages. This is essentially what Ry- suggested in a comment; e.g.:
Sub errorOutput(toggleError As Boolean, courseNumber As Integer)
lblError.Text = String.Empty
Dim err(6) As String
err(courseNumber) = "please ensure that what you input in Course " + courseNumber.ToString + " is a number between 0 and 100"
If toggleError = True Then
lblError.Text += err(courseNumber)
End If
End Sub

There is some built in things that can be used for validating user input. This is just some info I saved on the subject. Easy to use.
Validation
ErrorProvider
Private err As New ErrorProvider()
Or add to your form from Toolbox -> Components in Design View
.SetError(Control, “Error Message”)
Control.Validating
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text = "" Then
e.Cancel = True
err.SetError(TextBox1, "This text box cannot be blank.")
Else
err.Clear()
End If
End Sub

Related

Visual Basic Validation

I'm new to Visual Basics, and I tried implementing input validation for the Mark input in my application where the input can't be empty or < 0 or > 100 or isnumeric(Mark) = False or else an error message would be displayed. However, I tried leaving the input as empty or entering alphabetical values but it returned me a run time error instead. Could anyone assist me in some explanations as well as how to overcome this? Apologies if this is a dumb question.
Note: The data type for the variable "Mark" is set as single. Thank you for your time!
Sub InputMark()
4: For I = 0 To 3
Console.WriteLine("Please enter test marks for test " & I + 1)
Mark(I) = Console.ReadLine
While Mark(I) = Nothing Or Mark(I) < 0 Or Mark(I) > 100 Or IsNumeric(Mark(I)) = False
Console.WriteLine("Please enter valid test marks.")
GoTo 4
End While
Next
End Sub
A couple of things:
Turn option strict on: https://github.com/dday9/vb.net-tutorial/blob/master/Section%201/Chapter%201.md
Using Single.TryParse on the result of ReadLine.
ABANDON GOTO'! In this case a simple Do loop will suffice.
Take a look at this example:
Option Strict On
Option Explicit On
Imports System
Public Module Module1
Public Sub Main()
' Declare an array of Single values
Dim marks(3) As Single
' Loop from 0 to n (in this case 3)
For counter As Integer = 0 To marks.Length - 1
' Declare a variable to check if the conversion was succesful
Dim success As Boolean = False
' Start a Do/Until loop
Do
' Propt the user to enter something
Console.WriteLine("Please enter test marks for test " & counter + 1)
' Check if the conversion from ReadLine to a Single is valid
success = Single.TryParse(Console.ReadLine(), marks(counter)) AndAlso marks(counter) >= 0 AndAlso marks(counter) <= 100
' If not then scold the user
If (Not success) Then
Console.WriteLine("Please enter valid test marks.")
End If
Loop Until success
Next
' Debug - just print out the values of marks
For Each mark As Single In marks
Console.WriteLine(mark)
Next
End Sub
End Module
Live Demo: https://dotnetfiddle.net/guoAzP
The data type for the variable "Mark" is set as single.
One of the nice things about strongly-typed platforms like .Net is most of your validation rules are already enforced. You will not be able to assign a non-number value to Mark, and as a value-type it can't even be null (VB.Net's Nothing will evaluate to 0 for a Single type).
So what we need to do instead is back up, and find where the data is received from the user, before it's assigned to the Mark variable. Somewhere you'll have code like Mark(I) = Console.Readline(), or similar. That's where your testing needs to be. Check the string value received from the user before assigning it to the Single value. And when you come to that point, the best way to accomplish this testing is with the Single.TryParse() function. Then, you can verify the parsed Single value is within the correct range.
Okay, with more complete code we can start to give you some real improvements.
One suggestion is to think in terms of returning a value. It's better design to let this function return the array, rather than communicating through a global variable. I mention that here because it will also mean changing how you call this function.
That out of the way:
Function InputMarks() As Single()
Dim result(3) As Single
For I As Integer = 0 To 3
Dim ErrorMsg As String = ""
Do
Console.Write($"{ErrorMsg}Please enter test marks for test {I+1}: ")
Dim input As String = Console.ReadLine()
ErrorMsg = $"{vbCrLf}Please enter valid test marks.{vbCrLf}{vbCrLf}"
While Not Single.TryParse(input, result(I)) OrElse result(I) < 0 OrElse result(I) > 100
Next
Return result
End Function
No GOTO required or wanted.
If you haven't seen them yet, the $"strings" are using string interpolation and the OrElse operator instead of Or is to get short-circuiting behavior. Modern VB.Net should use OrElse and AndAlso instead of Or and And pretty much all the time.
In this case, using OrElse means we're sure Single.TryParse() completed successfully and we will have a valid number before attempting to verify the range. If the parse operation failed, the range tests won't even be attempted.
I'm going to break this into smaller functions.
First, here is a function to process a string, which returns either a number if it satisfies your conditions, or Single.NaN.
Private Function validateMarkOrNaN(input As String) As Single
Return If(Single.TryParse(input, validateMarkOrNaN) AndAlso 0 <= validateMarkOrNaN AndAlso validateMarkOrNaN <= 100, validateMarkOrNaN, Single.NaN)
End Function
Here is a second function which calls the first when it needs to process the user input. This function handles the flow of a single input. It can be called any number of times, requiring that you pass in the index only so it can be typed in the console.
Private Function getMarkInput(index As Integer) As Single
Dim result As Single
Do
Console.WriteLine($"Please enter test marks for test {index + 1}")
result = validateMarkOrNaN(Console.ReadLine())
If Single.IsNaN(result) Then Console.WriteLine("Please enter valid test marks.")
Loop While Single.IsNaN(result)
Return result
End Function
Your main program dictates the overall flow. Here you can declare how many marks will be read, and loop over your array, getting each input into each element.
Sub Main()
Dim numberOfMarks = 4
Dim Mark(numberOfMarks - 1) As Single
For i = 0 To numberOfMarks - 1
Mark(i) = getMarkInput(i)
Next
End Sub
Similar to your code, this will loop indefinitely as long as the user doesn't enter a valid float.

Display String From Text File in a Label Box in Visual Basic

So I am trying to make a code where the user inputs an ID number and receives the line of text that the ID corresponds to. I am having trouble with the code as I am unable to display the result (or correct result) in a label box.
For example:
If I type in ID 1, it displays the data that corresponds to ID 2, ID 2 corresponds to ID 3 and ID 3 ends the loop (there are only 3 records in the data currently).
I have included my code below
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Filename = "NamesAndAges.txt"
FileOpen(1, Filename, OpenMode.Input,,,)
Dim ID As Integer
ID = txtSearch.Text
Dim Found As Boolean
Found = False
Do While Not EOF(1) And Found = False
If LineInput(1).Contains(ID) Then
lblDisplaySearch.Text = LineInput(1)
Found = True
Else MsgBox("Not Found")
End If
Loop
FileClose(1)
End Sub
Thanks in advance, would also really appreciate if anyone could explain the code they use as I am still a visual basic beginner.
Every time you call LineInput(1), it reads a line, so you're reading a line and checking if it contains ID then reading another line and setting lblDisplaySearch.Text to that value.
Try something like this:
Dim line As String
Do While Not EOF(1) And Found = False
line = LineInput(1)
If line.Contains(ID) Then
lblDisplaySearch.Text = line
Found = True
Else MsgBox("Not Found")
End If
Loop
I would strongly suggest simplifying this code, by using File.ReadLines:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Filename = "NamesAndAges.txt"
Dim line = File.ReadLines(Filename).FirstOrDefault(Function(x) x.Contains(txtSearch.Text))
If line Is Nothing Then
MsgBox("Not Found")
Exit Sub
End If
lblDisplaySearch.Text = line
End Sub
The primary advantage is that you don't need to manage the Do While loop. Instead, you are passing the match condition (Function(x) x.Contains(txtSearch.Text)) to the FirstOrDefault method, which internally will find the first line matching the condition and return it, or return Nothing if it's not found.
For Each and IEnumerable
VB.NET allows you to loop over a set of items without knowing or caring about the index within the set. For example:
For Each x As String In File.ReadLines(Filename)
'do something with the line, which is now in x
Next
In order to use For Each with an object, that object has to implement a specific interface — the IEnumerable interface.
Interfaces
Interfaces guarantee that a given object has, or implements, specific members. In this case, if an object implements the IEnumerable interface, that means it has a GetEnumerator method, which the For Each uses under the hood.
IEnumerable(Of T)
The object returned from File.ReadLines implements another more advanced generic interface called IEnumerable(Of T). With this interface, the compiler can figure out automatically that each step of the For Each will be parsing a string, and we don't need to specify it as a string:
For Each x In File.ReadLines(Filename)
'x is known to be a String here
Next
Lambda expressions
The condition "the line which contains the search text" is written as a lambda expression, which (in this case) is made into a method without an explicit name or definition. This is convenient, because we don't have to write this:
Function ContainsCondition(line As String, toFind As String) As Boolean
Return line.Contains(toFind)
End Function`
every time we want to express a condition this way.
Type of x in the condition
Because File.ReadLines returns an IEnumerable(Of T), in this case an IEnumerable(Of String), the compiler can figure out that the condition is working on strings, so we don't have to specify that x is a string within the condition.

How to make string.contains work with a list

So I have this bot I'm making for someone that filters out curse words in a skype chat.
Instead of making it so my code is really long I want it so there is a huge list of curse words already loaded for example:
If Msg.Contains("swear1") Or Msg.Contains("swear2") Then
c.SendMessage("{---------Bot----------}" + vbNewLine + "DO NOT SWEAR!" + vbNewLine + "{-------------------------------------------}")
End If
I've tried creating an array and a string holding multiple values and didn't really work out too good as it didn't execute the function after someone said the trigger word. So I wanted to know if there is a way I can hold a huge list of curse words in one whatever without using
Msg.Contains("swear1")
Or
Msg.Contains("swear2")
etc etc, so everything would be held in one bit.
Any help would be appreciated :)
You use a Collection of Swear words and check the string against that. The .Any method takes the array and internally creates a For/loop with the word being the variable name for this loop and represents each string in the the array to test with our SwearWords.Contains(word) boolean expression, and if any of the expressions equates to True then it returns True.
Dim swearWordExists As Boolean = False
Dim msg As String = "swear1! has a swear word with extra text but still found"
Dim SwearWords As New List(Of String)
' fill it with your swear words
SwearWords.AddRange(New String() {"swear1", "swear2", "etc..."})
' then
If Not msg.Contains(" ") Then
' msg only has one word so check it
If SwearWords.Contains(msg) OrElse SwearWords.Any(Function(words) msg.Contains(words)) Then
swearWordExists = True
End If
Else
Dim words = Regex.Split(msg, "\W")
If Not words.Any(Function(word) SwearWords.Contains(word)) Then
If words.Any(Function(word) SwearWords.Any(Function(swear) word.Contains(swear))) Then
swearWordExists = True
End If
Else
swearWordExists = True
End If
End If
If swearWordExists Then
MessageBox.Show("Why are you swearing?")
End If
An easy but not super performant way would be to convert your string to a list then use the list intersect functionality
http://msdn.microsoft.com/en-us/library/vstudio/bb910215(v=vs.90).aspx
You could condense your code like this
Dim swears = New List(Of [String])() From {"swear1", "swear2"}
If Regex.IsMatch("[your message]", String.Format("({0})", String.Join("|", swears))) Then
MsgBox("Don't swear!")
End If
Where swears would be your list of all swears you don't want someone to say
What it does is it takes all strings in 'swears' and puts them into this format: (swear1|swear2) then regex will see if your message contains either 'swear1' or 'swear2' et cetera if you have more.

How to compare Val function with "" in Vb.Net

I am taking a user input a text box and then Validating it as follows:
Val(txt_score1.text)
Then I have to compare it with blank entry in that text box. Like this:
If (Val(txt_score1.Text) = "") Then....
I am receiving a conversion error. Because "" is String whereas Val is returning Integer.
How to overcome this??
You can use Integer.TryParse to determine if the value is a proper integer:
Dim x As Integer
If Integer.TryParse(TextBox1.Text, x) Then
MessageBox.Show(x)
Else
MessageBox.Show("'" + TextBox1.Text + "' is not a valid number")
End If
If you need to just check for a blank string, you can use String.IsNullOrEmpty on the text itself:
If String.IsNullOrEmpty(TextBox1.Text) Then
MessageBox.Show("String is empty")
End If
Val is a legacy function leftover from VB6 days and has some weird behavior if you don't know about it. I avoid it for this reason. For example, take the following cases and the output they generate:
MessageBox.Show(Val("")) '0
MessageBox.Show(Val("5")) '5
MessageBox.Show(Val("5e3")) '5000
MessageBox.Show(Val("5xyz")) '5

Hidden Features of VB.NET?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I have learned quite a bit browsing through Hidden Features
of C# and was surprised when I couldn't find something
similar for VB.NET.
So what are some of its hidden or lesser known features?
The Exception When clause is largely unknown.
Consider this:
Public Sub Login(host as string, user as String, password as string, _
Optional bRetry as Boolean = False)
Try
ssh.Connect(host, user, password)
Catch ex as TimeoutException When Not bRetry
''//Try again, but only once.
Login(host, user, password, True)
Catch ex as TimeoutException
''//Log exception
End Try
End Sub
Custom Enums
One of the real hidden features of VB is the completionlist XML documentation tag that can be used to create own Enum-like types with extended functionality. This feature doesn't work in C#, though.
One example from a recent code of mine:
'
''' <completionlist cref="RuleTemplates"/>
Public Class Rule
Private ReadOnly m_Expression As String
Private ReadOnly m_Options As RegexOptions
Public Sub New(ByVal expression As String)
Me.New(expression, RegexOptions.None)
End Sub
Public Sub New(ByVal expression As String, ByVal options As RegexOptions)
m_Expression = expression
m_options = options
End Sub
Public ReadOnly Property Expression() As String
Get
Return m_Expression
End Get
End Property
Public ReadOnly Property Options() As RegexOptions
Get
Return m_Options
End Get
End Property
End Class
Public NotInheritable Class RuleTemplates
Public Shared ReadOnly Whitespace As New Rule("\s+")
Public Shared ReadOnly Identifier As New Rule("\w+")
Public Shared ReadOnly [String] As New Rule("""([^""]|"""")*""")
End Class
Now, when assigning a value to a variable declared as Rule, the IDE offers an IntelliSense list of possible values from RuleTemplates.
/EDIT:
Since this is a feature that relies on the IDE, it's hard to show how this looks when you use it but I'll just use a screenshot:
Completion list in action http://page.mi.fu-berlin.de/krudolph/stuff/completionlist.png
In fact, the IntelliSense is 100% identical to what you get when using an Enum.
Have you noticed the Like comparison operator?
Dim b As Boolean = "file.txt" Like "*.txt"
More from MSDN
Dim testCheck As Boolean
' The following statement returns True (does "F" satisfy "F"?)'
testCheck = "F" Like "F"
' The following statement returns False for Option Compare Binary'
' and True for Option Compare Text (does "F" satisfy "f"?)'
testCheck = "F" Like "f"
' The following statement returns False (does "F" satisfy "FFF"?)'
testCheck = "F" Like "FFF"
' The following statement returns True (does "aBBBa" have an "a" at the'
' beginning, an "a" at the end, and any number of characters in '
' between?)'
testCheck = "aBBBa" Like "a*a"
' The following statement returns True (does "F" occur in the set of'
' characters from "A" through "Z"?)'
testCheck = "F" Like "[A-Z]"
' The following statement returns False (does "F" NOT occur in the '
' set of characters from "A" through "Z"?)'
testCheck = "F" Like "[!A-Z]"
' The following statement returns True (does "a2a" begin and end with'
' an "a" and have any single-digit number in between?)'
testCheck = "a2a" Like "a#a"
' The following statement returns True (does "aM5b" begin with an "a",'
' followed by any character from the set "L" through "P", followed'
' by any single-digit number, and end with any character NOT in'
' the character set "c" through "e"?)'
testCheck = "aM5b" Like "a[L-P]#[!c-e]"
' The following statement returns True (does "BAT123khg" begin with a'
' "B", followed by any single character, followed by a "T", and end'
' with zero or more characters of any type?)'
testCheck = "BAT123khg" Like "B?T*"
' The following statement returns False (does "CAT123khg" begin with'
' a "B", followed by any single character, followed by a "T", and'
' end with zero or more characters of any type?)'
testCheck = "CAT123khg" Like "B?T*"
Typedefs
VB knows a primitive kind of typedef via Import aliases:
Imports S = System.String
Dim x As S = "Hello"
This is more useful when used in conjunction with generic types:
Imports StringPair = System.Collections.Generic.KeyValuePair(Of String, String)
Oh! and don't forget XML Literals.
Dim contact2 = _
<contact>
<name>Patrick Hines</name>
<%= From p In phoneNumbers2 _
Select <phone type=<%= p.Type %>><%= p.Number %></phone> _
%>
</contact>
Object initialization is in there too!
Dim x as New MyClass With {.Prop1 = foo, .Prop2 = bar}
DirectCast
DirectCast is a marvel. On the surface, it works similar to the CType operator in that it converts an object from one type into another. However, it works by a much stricter set of rules. CType's actual behaviour is therefore often opaque and it's not at all evident which kind of conversion is executed.
DirectCast only supports two distinct operations:
Unboxing of a value type, and
upcasting in the class hierarchy.
Any other cast will not work (e.g. trying to unbox an Integer to a Double) and will result in a compile time/runtime error (depending on the situation and what can be detected by static type checking). I therefore use DirectCast whenever possible, as this captures my intent best: depending on the situation, I either want to unbox a value of known type or perform an upcast. End of story.
Using CType, on the other hand, leaves the reader of the code wondering what the programmer really intended because it resolves to all kinds of different operations, including calling user-defined code.
Why is this a hidden feature? The VB team has published a guideline1 that discourages the use of DirectCast (even though it's actually faster!) in order to make the code more uniform. I argue that this is a bad guideline that should be reversed: Whenever possible, favour DirectCast over the more general CType operator. It makes the code much clearer. CType, on the other hand, should only be called if this is indeed intended, i.e. when a narrowing CType operator (cf. operator overloading) should be called.
1) I'm unable to come up with a link to the guideline but I've found Paul Vick's take on it (chief developer of the VB team):
In the real world, you're hardly ever going to notice the difference, so you might as well go with the more flexible conversion operators like CType, CInt, etc.
(EDIT by Zack: Learn more here: How should I cast in VB.NET?)
If conditional and coalesce operator
I don't know how hidden you'd call it, but the Iif([expression],[value if true],[value if false]) As Object function could count.
It's not so much hidden as deprecated! VB 9 has the If operator which is much better and works exactly as C#'s conditional and coalesce operator (depending on what you want):
Dim x = If(a = b, c, d)
Dim hello As String = Nothing
Dim y = If(hello, "World")
Edited to show another example:
This will work with If(), but cause an exception with IIf()
Dim x = If(b<>0,a/b,0)
This is a nice one. The Select Case statement within VB.Net is very powerful.
Sure there is the standard
Select Case Role
Case "Admin"
''//Do X
Case "Tester"
''//Do Y
Case "Developer"
''//Do Z
Case Else
''//Exception case
End Select
But there is more...
You can do ranges:
Select Case Amount
Case Is < 0
''//What!!
Case 0 To 15
Shipping = 2.0
Case 16 To 59
Shipping = 5.87
Case Is > 59
Shipping = 12.50
Case Else
Shipping = 9.99
End Select
And even more...
You can (although may not be a good idea) do boolean checks on multiple variables:
Select Case True
Case a = b
''//Do X
Case a = c
''//Do Y
Case b = c
''//Do Z
Case Else
''//Exception case
End Select
One major time saver I use all the time is the With keyword:
With ReallyLongClassName
.Property1 = Value1
.Property2 = Value2
...
End With
I just don't like typing more than I have to!
The best and easy CSV parser:
Microsoft.VisualBasic.FileIO.TextFieldParser
By adding a reference to Microsoft.VisualBasic, this can be used in any other .Net language, e.g. C#
AndAlso/OrElse logical operators
(EDIT: Learn more here: Should I always use the AndAlso and OrElse operators?)
Static members in methods.
For example:
Function CleanString(byval input As String) As String
Static pattern As New RegEx("...")
return pattern.Replace(input, "")
End Function
In the above function, the pattern regular expression will only ever be created once no matter how many times the function is called.
Another use is to keep an instance of "random" around:
Function GetNextRandom() As Integer
Static r As New Random(getSeed())
Return r.Next()
End Function
Also, this isn't the same as simply declaring it as a Shared member of the class; items declared this way are guaranteed to be thread-safe as well. It doesn't matter in this scenario since the expression will never change, but there are others where it might.
In vb there is a different between these operators:
/ is Double
\ is Integer ignoring the remainder
Sub Main()
Dim x = 9 / 5
Dim y = 9 \ 5
Console.WriteLine("item x of '{0}' equals to {1}", x.GetType.FullName, x)
Console.WriteLine("item y of '{0}' equals to {1}", y.GetType.FullName, y)
'Results:
'item x of 'System.Double' equals to 1.8
'item y of 'System.Int32' equals to 1
End Sub
I really like the "My" Namespace which was introduced in Visual Basic 2005. My is a shortcut to several groups of information and functionality. It provides quick and intuitive access to the following types of information:
My.Computer: Access to information related to the computer such as file system, network, devices, system information, etc. It provides access to a number of very important resources including My.Computer.Network, My.Computer.FileSystem, and My.Computer.Printers.
My.Application: Access to information related to the particular application such as name, version, current directory, etc.
My.User: Access to information related to the current authenticated user.
My.Resources: Access to resources used by the application residing in resource files in a strongly typed manner.
My.Settings: Access to configuration settings of the application in a strongly typed manner.
Custom Events
Though seldom useful, event handling can be heavily customized:
Public Class ApplePie
Private ReadOnly m_BakedEvent As New List(Of EventHandler)()
Custom Event Baked As EventHandler
AddHandler(ByVal value As EventHandler)
Console.WriteLine("Adding a new subscriber: {0}", value.Method)
m_BakedEvent.Add(value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Console.WriteLine("Removing subscriber: {0}", value.Method)
m_BakedEvent.Remove(value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("{0} is raising an event.", sender)
For Each ev In m_BakedEvent
ev.Invoke(sender, e)
Next
End RaiseEvent
End Event
Public Sub Bake()
''// 1. Add ingredients
''// 2. Stir
''// 3. Put into oven (heated, not pre-heated!)
''// 4. Bake
RaiseEvent Baked(Me, EventArgs.Empty)
''// 5. Digest
End Sub
End Class
This can then be tested in the following fashion:
Module Module1
Public Sub Foo(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("Hmm, freshly baked apple pie.")
End Sub
Sub Main()
Dim pie As New ApplePie()
AddHandler pie.Baked, AddressOf Foo
pie.Bake()
RemoveHandler pie.Baked, AddressOf Foo
End Sub
End Module
I just found an article talking about the "!" operator, also know as the "dictionary lookup operator". Here's an excerpt from the article at: http://panopticoncentral.net/articles/902.aspx
The technical name for the ! operator
is the "dictionary lookup operator." A
dictionary is any collection type that
is indexed by a key rather than a
number, just like the way that the
entries in an English dictionary are
indexed by the word you want the
definition of. The most common example
of a dictionary type is the
System.Collections.Hashtable, which
allows you to add (key, value) pairs
into the hashtable and then retrieve
values using the keys. For example,
the following code adds three entries
to a hashtable, and looks one of them
up using the key "Pork".
Dim Table As Hashtable = New Hashtable
Table("Orange") = "A fruit"
Table("Broccoli") = "A vegetable"
Table("Pork") = "A meat"
Console.WriteLine(Table("Pork"))
The ! operator can be used to look up
values from any dictionary type that
indexes its values using strings. The
identifier after the ! is used as the
key in the lookup operation. So the
above code could instead have been
written:
Dim Table As Hashtable = New Hashtable
Table!Orange = "A fruit"
Table!Broccoli = "A vegetable"
Table!Pork = "A meat"
Console.WriteLine(Table!Pork)
The second example is completely
equivalent to the first, but just
looks a lot nicer, at least to my
eyes. I find that there are a lot of
places where ! can be used, especially
when it comes to XML and the web,
where there are just tons of
collections that are indexed by
string. One unfortunate limitation is
that the thing following the ! still
has to be a valid identifier, so if
the string you want to use as a key
has some invalid identifier character
in it, you can't use the ! operator.
(You can't, for example, say
"Table!AB$CD = 5" because $ isn't
legal in identifiers.) In VB6 and
before, you could use brackets to
escape invalid identifiers (i.e.
"Table![AB$CD]"), but when we started
using brackets to escape keywords, we
lost the ability to do that. In most
cases, however, this isn't too much of
a limitation.
To get really technical, x!y works if
x has a default property that takes a
String or Object as a parameter. In
that case, x!y is changed into
x.DefaultProperty("y"). An interesting
side note is that there is a special
rule in the lexical grammar of the
language to make this all work. The !
character is also used as a type
character in the language, and type
characters are eaten before operators.
So without a special rule, x!y would
be scanned as "x! y" instead of "x !
y". Fortunately, since there is no
place in the language where two
identifiers in a row are valid, we
just introduced the rule that if the
next character after the ! is the
start of an identifier, we consider
the ! to be an operator and not a type
character.
This is built-in, and a definite advantage over C#. The ability to implement an interface Method without having to use the same name.
Such as:
Public Sub GetISCSIAdmInfo(ByRef xDoc As System.Xml.XmlDocument) Implements IUnix.GetISCSIInfo
End Sub
Forcing ByVal
In VB, if you wrap your arguments in an extra set of parentheses you can override the ByRef declaration of the method and turn it into a ByVal. For instance, the following code produces 4, 5, 5 instead of 4,5,6
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim R = 4
Trace.WriteLine(R)
Test(R)
Trace.WriteLine(R)
Test((R))
Trace.WriteLine(R)
End Sub
Private Sub Test(ByRef i As Integer)
i += 1
End Sub
See Argument Not Being Modified by Procedure Call - Underlying Variable
Passing parameters by name and, so reordering them
Sub MyFunc(Optional msg as String= "", Optional displayOrder As integer = 0)
'Do stuff
End function
Usage:
Module Module1
Sub Main()
MyFunc() 'No params specified
End Sub
End Module
Can also be called using the ":=" parameter specification in any order:
MyFunc(displayOrder:=10, msg:="mystring")
The Using statement is new as of VB 8, C# had it from the start. It calls dispose automagically for you.
E.g.
Using lockThis as New MyLocker(objToLock)
End Using
Import aliases are also largely unknown:
Import winf = System.Windows.Forms
''Later
Dim x as winf.Form
Consider the following event declaration
Public Event SomethingHappened As EventHandler
In C#, you can check for event subscribers by using the following syntax:
if(SomethingHappened != null)
{
...
}
However, the VB.NET compiler does not support this. It actually creates a hidden private member field which is not visible in IntelliSense:
If Not SomethingHappenedEvent Is Nothing OrElse SomethingHappenedEvent.GetInvocationList.Length = 0 Then
...
End If
More Information:
http://jelle.druyts.net/2003/05/09/BehindTheScenesOfEventsInVBNET.aspx
http://blogs.msdn.com/vbteam/archive/2009/09/25/testing-events-for-nothing-null-doug-rothaus.aspx
If you need a variable name to match that of a keyword, enclose it with brackets. Not nec. the best practice though - but it can be used wisely.
e.g.
Class CodeException
Public [Error] as String
''...
End Class
''later
Dim e as new CodeException
e.Error = "Invalid Syntax"
e.g. Example from comments(#Pondidum):
Class Timer
Public Sub Start()
''...
End Sub
Public Sub [Stop]()
''...
End Sub
There are a couple of answers about XML Literals, but not about this specific case:
You can use XML Literals to enclose string literals that would otherwise need to be escaped. String literals that contain double-quotes, for instance.
Instead of this:
Dim myString = _
"This string contains ""quotes"" and they're ugly."
You can do this:
Dim myString = _
<string>This string contains "quotes" and they're nice.</string>.Value
This is especially useful if you're testing a literal for CSV parsing:
Dim csvTestYuck = _
"""Smith"", ""Bob"", ""123 Anywhere St"", ""Los Angeles"", ""CA"""
Dim csvTestMuchBetter = _
<string>"Smith", "Bob", "123 Anywhere St", "Los Angeles", "CA"</string>.Value
(You don't have to use the <string> tag, of course; you can use any tag you like.)
DateTime can be initialized by surrounding your date with #
Dim independanceDay As DateTime = #7/4/1776#
You can also use type inference along with this syntax
Dim independanceDay = #7/4/1776#
That's a lot nicer than using the constructor
Dim independanceDay as DateTime = New DateTime(1776, 7, 4)
You can have 2 lines of code in just one line. hence:
Dim x As New Something : x.CallAMethod
Optional Parameters
Optionals are so much easier than creating a new overloads, such as :
Function CloseTheSystem(Optional ByVal msg AS String = "Shutting down the system...")
Console.Writeline(msg)
''//do stuff
End Function
Title Case in VB.Net can be achieved by an old VB6 fxn:
StrConv(stringToTitleCase, VbStrConv.ProperCase,0) ''0 is localeID
Properties with parameters
I have been doing some C# programming, and discovered a feature that was missing that VB.Net had, but was not mentioned here.
An example of how to do this (as well as the c# limitation) can be seen at: Using the typical get set properties in C#... with parameters
I have excerpted the code from that answer:
Private Shared m_Dictionary As IDictionary(Of String, Object) = _
New Dictionary(Of String, Object)
Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
If m_Dictionary.ContainsKey(Key) Then
Return m_Dictionary(Key)
Else
Return [String].Empty
End If
End Get
Set(ByVal value As Object)
If m_Dictionary.ContainsKey(Key) Then
m_Dictionary(Key) = value
Else
m_Dictionary.Add(Key, value)
End If
End Set
End Property