-3

I am trying to get input from user by using Microsoft.VisualBasic.dll. Then convert the input from [string] to [char] type. But it gives me this error when I run the code:

*An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
String must be exactly one character long.*

Sample code:

      string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);

      char direction = System.Convert.ToChar(directions);

Any idea how to solve this? Thanks in advance.

gonzalloe
  • 313
  • 3
  • 7
  • 22
  • Of course, I know what this "_String must be exactly one character long_" means. For `directions`, I didn't set the length. But, after several tries, I found that any input that more than 1 value will get this error. Instead, only input with 1 value (alphanumeric) works fine. – gonzalloe Nov 08 '18 at 03:18
  • 1
    Remember a char is a single character, while a string is 0 or more characters strung together. – Stephen Wrighton Nov 08 '18 at 03:32
  • You didn't set the length, sure. But you set a value of _specific_ length, no? I think that 1 try is enough to determine that the string "12" is length of 2. – vasily.sib Nov 08 '18 at 03:33

2 Answers2

2

You can do this: Its always strongly recommended to catch FormatException and ArgumentNullException like this link:

https://learn.microsoft.com/en-us/dotnet/api/system.convert.tochar?view=netframework-4.7.2#System_Convert_ToChar_System_String_

char direction;

string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);

if(!string.IsNullOrEmpty(directions) && directions.Trim().Length == 1)
  direction = System.Convert.ToChar(directions);
else {
  direction = directions.FirstOrDefault(); // if thats what your logic
}

or you can use:

char direction = directions.FirstOrDefault();
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
0

Why did you put "Default" as default response? You either leave it blank, or put "1" or "2" there.

Also check for user's answer before converting to direction :

If directions <> "1" And directions <> "2" Then
    'display error message to user
Else
    char direction = System.Convert.ToChar(directions);
    'proceed with your business logic
End If
Daniel Wu
  • 124
  • 1
  • 9