我想填充GridView读取会话变量Id,但我收到的错误是将数据类型转换为{"Conversion failed when converting the nvarchar value 'finalProject.User' to data type int."}
,但我的数据库表中没有nvarchar值,它已经是int。我该如何解决呢?
的 finalProject.User
public class User
{
public int Id { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string email { get; set; }
}
用户对象
User u = new User();
u.Id = Convert.ToInt32(dr["Id"]);
u.name = dr["name"] != DBNull.Value ? dr["name"].ToString() : string.Empty;
u.surname = dr["surname"] != DBNull.Value ? dr["surname"].ToString() : string.Empty;
u.email = dr["email"] != DBNull.Value ? dr["email"].ToString() : string.Empty;
Session["user"] = u;
我的代码
public partial class MyConferences : System.Web.UI.Page
{
internal User user;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
object user = Session["user"];
if(user != null)
{
user = Session["user"] as User;
}
string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
using(SqlConnection con = new SqlConnection(constr))
{
string query = "select Conferences.conferenceName , Conferences.conferenceDate , Conferences.conferencePlace , Conferences.category from Conferences inner join Users on Conferences.fk_Users = Users.Id where Users.Id = @UserId";
using(SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
Convert.ToInt32(Session["UserId"]);
SqlParameter prm = cmd.Parameters.AddWithValue("@UserId", user.ToString());
if(user == null)
{
prm.Value = DBNull.Value;
}
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
}
答案 0 :(得分:3)
mark_h是对的,您将string
值传递给int
,但您也不知道如何传递id
。如果你给出正确的类型而不是object
会更好。
object user = Session["user"] as User;
将是
User user = Session["user"] as User;
和
SqlParameter prm = cmd.Parameters.AddWithValue("@UserId", user.Id);
答案 1 :(得分:1)
您似乎正在尝试将字符串作为整数传递;
SqlParameter prm = cmd.Parameters.AddWithValue("@UserId", user.ToString());
UserId是一个整数,但user.ToString()是一个字符串。您的意思是将其用作参数吗?
Convert.ToInt32(Session["UserId"])
答案 2 :(得分:1)
我认为你传递了错误的值" user.ToString()"而#34;会话[" UserId"]"。用户是一个对象,userId看起来像一个id值。在发送价值之前不要忘记转换。