user3166918
user3166918

Reputation: 41

Specified cast is not valid casting a SqlParameter

This code gives an InvalidCastException: Specified cast is not valid.

// getting the user id

SqlCommand cmd2 = new SqlCommand("getId", conn);
cmd2.CommandType = CommandType.StoredProcedure;

cmd2.Parameters.Add(new SqlParameter("@email", email));

// output parm
SqlParameter user_id = cmd2.Parameters.Add("@user_id", SqlDbType.Int);
count.Direction = ParameterDirection.Output;

conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

Session["user_id"] = user_id;

Response.Redirect("~/CheckProfile.aspx");

And then when using this user_id in another page, I write this:

int user_id = (int)(Session["user_id"]);

Upvotes: 0

Views: 1309

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113322

You're storing SqlParameter in Session["user_id"] and then attempting to cast that to int. That cast cannot be done.

Instead do:

Session["user_id"] = (int)user_id.Value;

Then you will have stored the int, and be able to retrieve it as such. You may though want to cast to int? because then you can deal with it not having been set:

int? userIDMaybe = (int?)Session["user_id"];
if(userIDMaybe.HasValue)
{
  int userID = userIDMaybe.Value;
  /* ... */
}
else
{
  /* Code to handle not logged in yet... */
}

Upvotes: 4

Morten Anderson
Morten Anderson

Reputation: 2321

This should do it

SqlCommand cmd2 = new SqlCommand("getId", conn);
cmd2.CommandType = CommandType.StoredProcedure;

cmd2.Parameters.Add(new SqlParameter("@email", email));

// output parm
SqlParameter user_id = new SqlParameter("@user_id", SqlDbType.Int);
user_id.Direction = ParameterDirection.Output;
cmd2.Parameters.Add(user_id);

conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();

Session["user_id"] = cmd2.Parameters["@user_id"].Value;

Response.Redirect("~/CheckProfile.aspx");

Upvotes: 1

Related Questions