Let's say your input is ABC
, after clicking on button1
, your encoded text will be "65 66 67 "
. (Notice the extra space at the end of the string.)
So when you click on button2
, you will get:
messageCodes[0]: "65"
messageCodes[1]: "66"
messageCodes[2]: "67"
messageCodes[3]: "" // <-- An extra empty string... Bad!
And when you do the int.Parse
for the last item (the empty string), it will fail.
What you need to do is to trim the text before splitting it, as in:
string[] messageCodes = decoderBox.Text.Trim().Split(' ');
Also, as an aside, you should move the encoderBox.Text = "";
out of the for
loop in order for it to work properly, as in:
encoderBox.Text = "";
for (int i = 0; i < codes.Length; i++)
{
codes[i] = int.Parse(messageCodes[i]);
letters[i] = Convert.ToChar(codes[i]);
encoderBox.Text += letters[i];
}