Search code examples
c#stringsubstringmessagebox

C# String.SubString With MessageBox Does Not Display Anything


I am trying to display part of a string using a MessageBox, for this I use the String.SubString method. However when I run the code the MessageBox is not displayed and no error is thrown.

For troubleshooting purposes I display the entire string in a MessageBox before trying to display the substring.

This displays the following (Received |<BID>22|):

I want to display the number part of the string, however when I try doing this nothing is displayed. Can anyone see what is going wrong please? Here is the code:

public void parseMessage(string theMessage)
{
    String message = theMessage.Replace("\n", String.Empty);

    MessageBox.Show("Received |" + message + "|");

    String zoneNumber = message.Substring(5, message.Length);

    if (message.StartsWith("<BID>"))
    {
        MessageBox.Show("Bid received for zone " + zoneNumber);
    }
}

Solution

  • I can't access your linked image, so I don't know for certain what message contains, but

    String zoneNumber = message.Substring(5, message.Length);
    

    should throw an exception as it would overflow the length of the string by 5 characters.

    Use

    String zoneNumber = message.Substring(5);
    

    instead.