Why is these text comparisons not working

In my little program I have a richtextbox and a button. When clicking the button this code is run and when I debug I see that my in the richtextbox entered text is indeed in the txt variable. But when I for example enters 'hej' the first if statement is skipped, why txt = hej so txt=="hej" ought to be true! But isn't.

private void Button_Click(Object sender, System.EventArgs e)

{

String txt = new String();

txt = richTextBox.get_Text();

if (txt == "hej")

Button.set_Text("OK");

else if (txt == "q")

Application.Exit();

else

{

Button.set_Text(richTextBox.get_Text());

}

}




Answer this question

Why is these text comparisons not working

  • J. Aldrin

    String is an object to use == would only compare memory address locations, which cannot equal. If you use the .equals() method for the string you then compare the string values of the object.

    this is how it should look.

    private void Button_Click(Object sender, System.EventArgs e)

    {

    String txt = new String();

    txt = richTextBox.get_Text();

    if (txt.equals( "hej"));

    Button.set_Text("OK");

    else if (txt.equals("q"));

    Application.Exit();

    else

    {

    Button.set_Text(richTextBox.get_Text());

    }

    }



  • jesse_j3000

    To compare two Strings please use Equals method of String class.

    Above code should be

    if (txt.Equals("hej"))



  • SmithaNarreddi

    Hi Jan Friberg,

    You can refer to the below link for the operators behaviour.

    http://msdn2.microsoft.com/en-us/library/ms177697(VS.80).aspx

    You can use read the below link for your purpose.

    http://msdn2.microsoft.com/en-us/library/ms177895(VS.80).aspx

    Thanks,

    P.Shivaram.



  • Why is these text comparisons not working