Search code examples
c#winformstextboxmessagebox

Why is a string working in MessageBox but not in the if statement


            WebClient wc = new WebClient();
            string code = wc.DownloadString("link");
            MessageBox.Show(code); // CODE SHOWS IN MESSAGEBOX CORRECTLY.
            if (textbox.Text == code)
            {
                MessageBox.Show("Key Approved!");
                try
                {
                    Form1 Form1 = new Form1();
                    Form1.Show();
                    this.Hide();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("This Key is incorrect.");
            }

The text inside the Textbox is the Text in the code string, although textbox.Text == code is false and it returns to the else argument.

Any idea why this is happening?


Solution

  • Text inside the Textbox is the Text in the code string, although textbox.Text == code is false and it returns to the else argument.

    I don't believe you. And since you failed to show evidence for this, I'm convinced you are wrong.

    This suggests that TextBox.Text is not identical to code. If they look the same, then the difference is probably something like extra spaces, upper vs. lower case, or other minor differences.

    The only other imaginable cause is that you've overridden the string equality operator somehow to do something unexpected.

    Try this code instead:

    Test(TextBox.Text, code);
    
    void Test(string textbox, string code)
    {
        if (textbox.Length != code.Length)
        {
            MessageBox.Show("Strings are different lengths!");
            return;
        }
    
        for (int i = 0; i < textbox.Length; i++)
        {
            if (textbox[i] != code[i])
            {
                MessageBox.Show(string.Format("'{0}' does not equal '{1}'", textbox[i], code[i]));
                return;
            }
        }
        MessageBox.Show("Strings are identical!");
    }