Search code examples
c#.netstringcharinputbox

How to solve String must be exactly one character long? C# .net error


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.


Solution

  • 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();