You have a program that needs to parse commands and then based on the result do
String enumeration in VB.NET would be the ideal answer, but enumerations in .NET
are limited to numbers.
After a lot of web searching for a quick few lines of code, I put this code together to help others as many sites show more complex usage of
enumerations as set examples.
The only rule in your program's command strings is keep the string simple without spaces, when you put them into your enumeration.
This little code snippet will then make parsing your command strings simple.
Using the code
Using the code will just require a new VB.NET Windows Forms project with a Textbox (
Textbox1) , Label (
Label1), and Button (
All your program command strings are put in the enumeration "
Running the example will just need you to enter in the input box the exact
string as found in your
Enum. The label will show if your command was parsed
Note the most important line in the code uses the
[Enum].Isdefined function which checks if your string is in the
Enum which returns true or false. Then we can parse the test string to see if a match is found. The matching string can then be used in the "
Select Case" to perform actions on the command.
Public Class Form1
Private Enum ProgramCommands
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim sCommandToTest As String = TextBox1.Text.ToUpper
If CBool(CType([Enum].IsDefined(GetType(ProgramCommands), sCommandToTest), ProgramCommands)) Then
Dim testcase As ProgramCommands = _
CType([Enum].Parse(GetType(ProgramCommands), sCommandToTest, True), ProgramCommands)
Select Case testcase
Label1.Text = "Run motor action stuff here"
Label1.Text = "Stop motor action Stuff here"
Label1.Text = "Move arm action stuff here"
Label1.Text = "Fire gun action stuff here"
Label1.Text = "Should never get here!"
Label1.Text = "False :- No such command"
Points of Interest
For further details on string enumerations, please see
which will outline more details. In fact the MSN example gave me the idea that a more simple answer was needed!
First version: 13/08/2012.
David Rathbone is an electronics and software design engineer and has been in commercial hardware and software development for over 30 years. He has designed a number of products that are now used everyday all over the world.