Reputation: 73
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?
I tried converting this (bool)reader["IsAdmin"].ToInt32
, but it shows error.
I tried changing it to integer but then it shows me 1's and 0's.
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
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
Upvotes: 4