0

I assigned a string from database data to c# variable. The string is being assigned properly. I tried using a message box and print the variable and it prints the value properly as a string. But when I compare that variable with another string it doesn't work. It always prints "This is Admin" although the two sides of the comparison is same.

SqlDataReader uid = cmd1.ExecuteReader();
while (uid.Read())
{
   string usertype = Convert.ToString(uid[0]);
   if (usertype =="User")
   {
      MessageBox.Show("This is User");
   }
   else
   {
      MessageBox.Show("This is Admin");
   }
}
uid.Close();
Anny
  • 13
  • 4

1 Answers1

0

Are you tried something like string.Equals(string) function ?

using System;

public class Program
{
    public static void Main()
    {
        String      str1 = "abcd";
        String      str2 = "abcd";
        String      str3 = "ABCD";

        Console.WriteLine(str1.Equals(str2)); //True

        Console.WriteLine(str1.Equals(str3)); //False for upper case

        Console.WriteLine(str1.Equals(str3.ToLower())); //True Recommend this because you can compare the user with User and this isn't same.
    }
}

Output: https://dotnetfiddle.net/Pl72SQ

Documentation:

https://learn.microsoft.com/es-es/dotnet/api/system.string.equals?view=netframework-4.8#System_String_Equals_System_String_System_String_

deon cagadoes
  • 582
  • 2
  • 13
  • 3
    *You cant compare 2 string with ==* Yes, you can. You should also add to your answer all relevant code instead of posting a link. – Guy Jul 21 '19 at 09:12
  • @Guy Sorry for that i fixed. – deon cagadoes Jul 21 '19 at 09:31
  • 1
    This option worked for me. Thank you. Didn't know that two srtings cannot be compared using == till now. – Anny Jul 21 '19 at 09:33
  • Yes, for example in C++ you can't compare 2 strings with == operator, i suppose this something similar on C#, don't remember put how Correct answer! – deon cagadoes Jul 21 '19 at 09:36
  • 1
    @Anny you can compare strings with `==` https://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same – Guy Jul 21 '19 at 09:41