hi. im having problems with comparing a string and a string array. I know it should be as simple as something like if(str == strn[0]) and if this is true, it will go to that if block statement. I've tried all kinds of test already and it seems that whether it is a string or a string array it still does not satisfy even if they have the same string values. I wonder why. Here's my code by the way. I initially try to read from a database a certain column then started the comparison process.

string connString = @"server = .\sqlexpress;
                                  integrated security = true;

                                  database = mmda";
            string sql = @"SELECT PlateNo FROM Records";
            SqlConnection conn = new SqlConnection(connString);

            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    if (rdr[0].ToString() != "")
                    {
                            strArray[ctr] = rdr[0].ToString();
                            ctr++;
                    }
                }                
               foreach (string val in strArray)
               {
                    if (val == txtBxPlate.Text)
                       break;
                    else { MessageBox.Show("NOT!"); break; }
               }
               MessageBox.Show("SAME!");

                rdr.Close();
            }

I've also tried:

if (txtBxPlate.Text == strArray[0]) MessageBox.Show("SAME!");
                else
                {
                    MessageBox.Show("NOT THE SAME!");
                }

This still did not work. It only satisfies when it is compared to itself like

strArray[0] == strArray[0]

. Even if you manually compare it to a string. Say...

str1 = "hello"

to strArray[0] who also contains "hello." It still goes to the else statement. Can anyone help me with this? ='(

Hi,
I checked this, It is working.
My COding

string name = "case";
    string[] names = { "case","Case", "cAse"};
    int i = 0;

    for (i = 0; i < names.Length; i++ )
    {
        if (name == names[i] )
            MessageBox.Show("Same " + i);
        else
            MessageBox.Show("Not Same " + i);
    }

I think the problem in reading values to strArray []
If you using Visual Studio IDE, Run the program in Debug Mode and Add Watch to strArray[] check the values.

Instead of comparing it "==" operator use either string.compare or string.equals method.

Did you try ?

if (txtBxPlate.Text.CompareTo(strArray[0]) == 0) MessageBox.Show("SAME!");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.