0

My Users table has a field called Admin which is tinyint(1). 1 for admin, 0 for normal user.

I want to set a session variable when users log in that is either true or false depending on if they're admin or not.

if ((int)Reader["Admin"] == 0)
{
    HttpContext.Current.Session["Admin"] = false;
}
else
{
    HttpContext.Current.Session["Admin"] = true;
}

Reader is a SqlDataReader. The code produces the following error:

System.InvalidCastException: Specified cast is not valid.

How can I properly cast Reader["Admin"] to an int?

James Dawson
  • 5,309
  • 20
  • 72
  • 126

3 Answers3

3

That's because tinyint gets turned into a System.Byte which can't be explicitly cast to an System.Int32

You will have to use Convert.ToInt32(Byte)

Josh
  • 44,706
  • 7
  • 102
  • 124
0

tinyint converts to Byte in C#. Change the cast/condtional to

 (Byte)Reader["Admin"] == 0
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
0

Check the below links

How can you convert "tinyint" of t-sql to integer in c#?

MSDN Reference about CLR Type conversion

Community
  • 1
  • 1
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120