Trying to get currently logged in users userid and use it in an SQL query from behindcode to fill a gridview but its not working any ideas what I'm doing wrong. I keep getting a null value error. Also I'm trying to only use the Microsoft.AspNet.Identity if thats even possible
pageload
if (!IsPostBack)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.InsertParameters["luser"].DefaultValue = User.Identity.GetUserId();
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = @luser";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
UPDATE:
I was able to get the results that i wanted by adding the requested directly into the SQL query. Is there any reason that i should not add it that what
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = '"+User.Identity.GetUserId()+"'";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
Solution = Friending = '"+User.Identity.GetUserId()+"'";
If are trying to get user identity from HttpContext then try following code instead. Identity store username/id (based on your logic) in Name property.
Also the object reference error is coming because you have not added "luser" in InsertParameter, but trying to set default value for it. I have added this SqlDataSource1.InsertParameters.Add(new Parameter("luser"));
to make sure it have the parameter, before you use it
if (!IsPostBack)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.InsertParameters.Add(new Parameter("luser"));
SqlDataSource1.InsertParameters["luser"].DefaultValue = HttpContext.Current.User.Identity.IsAuthenticated ? HttpContext.Current.User.Identity.Name : String.Empty;
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = @luser";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.