views:

44

answers:

2

I need to check if a character is a valid Key (type) in VB.NET (I need to turn "K" into Keys.K, for example). I am currently doing this to convert it:

Keys.Parse(GetType(Keys), key, False)

However, if key is not valid it throws an exception. How can I check if key is a valid character?

A: 

You should use Keys.TryParse (Available in .Net 4.0). It will return true if key is a valid key, false otherwise (Doesn't throw).

krolth
+2  A: 

Enums do not have a TryParse method, therefore, you could do something like this:

Public Function IsValidKey(ByVal key As String) As Keys

    If Not [Enum].IsDefined(GetType(Keys), key) Then
        Return Keys.None
    End If

    Return CType(Keys.Parse(GetType(Keys), key, False), Keys)

End Function

Use it like this:

Dim k As Keys = IsValidKey("K")
If k <> Keys.None Then
  ' valid key
else
  ' invalid key
End If
Perfect, exactly what I was looking for. Thanks!
Steven
@Steven - Glad I could help. Would please upvote this answer if you found it useful. Thanks.