xVenum.dll
xVenum.dll

Reputation: 73

How to fix "Specified cast is not valid" error in C#?

The problem is, I need to show a list in my application.

I made a SQL int type for IsAdmin as I was asked, and in school they told me to make that int show bool in application, more precisely to show IsAdmin = True or False?

But when I start application and when I pass the login screen the exception shows with message:

"Specified cast is not valid!"

What I need to do?

        public static List<Korisnik> GetAllUsers() {

            List<Korisnik> korisnici = new List<Korisnik>();
            Korisnik korisnik = null;

            using (SqlConnection conn = new SqlConnection()) {

                conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
                conn.Open();

                SqlCommand command = new SqlCommand("SELECT ID, UserName, UserPass, IsAdmin FROM Users01", conn);

                using (SqlDataReader reader = command.ExecuteReader()) {

                    while (reader.Read()){

                        korisnik = new Korisnik((int)reader["ID"], (string)reader["UserName"], (string)reader["UserPass"], (bool)reader["IsAdmin"]);
                        korisnici.Add(korisnik);

                    }

                }

            }

            return korisnici;

        }

Upvotes: 2

Views: 463

Answers (1)

user585968
user585968

Reputation:

Change this line:

korisnik = new Korisnik((int)reader["ID"], 
                        (string)reader["UserName"], 
                        (string)reader["UserPass"], 
                        (bool)reader["IsAdmin"]);

...to:

korisnik = new Korisnik((int)reader["ID"], (string)reader["UserName"], 
                        (string)reader["UserPass"], 
                        ((int)reader["IsAdmin"]) > 0 ? true : false ); // convert from int to bool

The conversion is necessary because you can't just assign an int to a bool. I am assuming that in the database, anything greater than 0 means that the user is an administrator.

I know it is a homework question, but going forward, it is much better to use boolean types in the database (in this case BIT) because

  1. they take less room in the database (more efficient)
  2. makes it more apparent what the column's purpose is
  3. eliminates conversion problems such that posted in the question

Tell me more about BIT

Upvotes: 4

Related Questions