when i try to open a image it says:
System.NullReferenceException: Object reference not set to an instance of an object. at usercontrol_comments.fill() in
d:\inetpub\vhosts\workpage.in\httpdocs\usercontrol\comments.ascx.cs:line 65
I don't believe it's loosing the Session variables. The problem is your local variables such as UID are not persisetent. Every time you create a postback to any part of the page (not necessarily clicking on a button in the user control) your UID variable
is reset. The simples thing to do is simply make UID a property so that every time you access it, it returns the session variable.
If you were truly loosing the session variables then you would be getting errors every time you tried to access Session["uid"] because if it was lost, the value would be null and any use of it would have thrown an object reference not found
error.
Don't forget to mark useful responses as Answer if they helped you towards a solution.
Marked as answer by Dino He - MSFT on Mar 22, 2012 09:45 AM
amit.saab
Member
18 Points
8 Posts
User control unable to load session variable
Mar 15, 2012 03:00 PM|LINK
Hey all,
m having this problem with my site...
Its kinna social networking site. On login the user id gets loaded as session variable "uid" and its getting passed to all the pages fine
I have defined a user control to load the comments and likes of a particular image uploaded by user
here is the code for image.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image.aspx.cs" Inherits="Image" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ Register Src="~/usercontrol/comments.ascx" TagName="comments" TagPrefix="UC" %> <%@ Register Src="~/usercontrol/Likes.ascx" TagName="likes" TagPrefix="UC" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script> <!-- Google Font and style definitions --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:regular,bold" /> <link rel="stylesheet" href="css/style.css" /> <!-- include the skins (change to dark if you like) --> <link rel="stylesheet" href="css/light/theme.css" id="themestyle" /> <!-- Use Google CDN for jQuery and jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript"></script> <style>//style definations here </style> </head> <body style="text-align: center"> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Image ID="imgImage" runat="server" CssClass="myimage" /> <br /> <asp:Label ID="lblDescription" runat="server" Text=""></asp:Label> <br /> <table style="margin: 0px"> <tr> <td> <%--likes usercontrol here--%> <UC:likes ID="likes" runat="server" /> </td> <td> <div align="right" style="font-size: 15px; font-weight: bolder; padding-right: 40px"> <span id="lblCurrent"></span> </div> </td> </tr> </table> <%-- comments usercontrol here--%> <UC:comments ID="comments" runat="server" IsOwner="false" /> </form> <div runat="server" id="divRestricted"> This Content is only available to certain Users. </div> </body> </html>image.aspx.cs is:
using System; using System.Data; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; public partial class Image : System.Web.UI.Page { private string cmd = ""; private string imgid = ""; private string LoggedinID = ""; private DataFunctions oDF = new DataFunctions(); private string Uid = ""; private void Fill() { try { this.imgid = base.Request["id"].ToString(); if (base.Request["uid"] != null) { this.Uid = base.Request["uid"].ToString(); } this.LoggedinID = this.Session["uid"].ToString(); bool flag = false; bool flag2 = false; if (this.Uid == this.LoggedinID) { flag = true; } else { this.cmd = "select uid from useraccount where uid in ( select * from dbo.Split((select friendsid from friends where uid ='" + this.Uid + "'),','))"; if (this.oDF.ExcuteQuery(this.cmd).Tables[0].Rows.Count > 0) { flag2 = true; } } this.cmd = "SELECT * FROM images where imageid='" + this.imgid + "'"; DataTable table = this.oDF.ExcuteQuery(this.cmd).Tables[0]; int num = 0; try { num = Convert.ToInt16(table.Rows[0]["pref"].ToString()); } catch { } if (((num == 0) || ((num == 1) && (flag2 || flag))) || ((num == 2) && flag)) { this.imgImage.ImageUrl = "api/image.ashx?width=640&height=480&name=" + table.Rows[0]["filename"].ToString(); this.lblDescription.Text = table.Rows[0]["description"].ToString(); this.divRestricted.Visible = false; } else { this.form1.Visible = false; this.divRestricted.Visible = true; } } catch (Exception exception) { base.Response.Write(this.oDF.ExceptionHandler(exception)); } } protected void Page_Load(object sender, EventArgs e) { this.likes.ArticleID = this.comments.ArticleID = base.Request["id"].ToString(); if (!base.IsPostBack) { this.Fill(); } } }User control comments.ascx.cs is:
using System; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; public partial class usercontrol_comments : System.Web.UI.UserControl { private string cmd = ""; private DataFunctions oDF = new DataFunctions(); private string Uid = ""; protected void btnAddComment_Click(object sender, EventArgs e) { try { this.Uid = base.Session["uid"].ToString(); string str = this.oDF.GenerateCommentID(); string str2 = this.tamessage.Text.Replace("\r", "<br />").Replace("\n", "<br />").Trim(); this.cmd = "INSERT INTO [comments]([commentid],[articleid],[byuid],[addedon],[description]) VALUES('{0}','{1}','{2}','{3}','{4}')"; this.cmd = string.Format(this.cmd, new object[] { str, this.ArticleID, this.Uid, DateTime.Now, str2 }); this.oDF.ExcuteQuery(this.cmd); this.cmd = "INSERT INTO [activity]([byuid],[activity],[articleid],[doneon]) VALUES('{0}','{1}','{2}','{3}')"; this.cmd = string.Format(this.cmd, new object[] { this.Uid, "comment", this.ArticleID, DateTime.Now }); this.oDF.ExcuteQuery(this.cmd); this.oDF.CreateNotification(this.Uid, this.ArticleID, "comment"); } catch (Exception exception) { this.lblMsg.Text = exception.ToString(); } finally { this.tamessage.Text = ""; this.fill(); } } protected void dlComments_ItemCommand(object source, DataListCommandEventArgs e) { if (e.CommandName == "Delete") { try { this.cmd = "Delete from comments where commentid='" + e.CommandArgument + "'"; this.oDF.ExcuteQuery(this.cmd); } catch (Exception exception) { this.lblMsg.Text = exception.ToString(); } finally { this.fill(); } } } private void fill() { try { this.dlComments.DataSource = null; this.dlComments.DataBind(); this.Uid = base.Session["uid"].ToString(); this.cmd = "SELECT useraccount.name, comments.* FROM comments INNER JOIN useraccount ON comments.byuid = useraccount.uid where comments.articleid='" + this.ArticleID + "'"; DataTable table = this.oDF.ExcuteQuery(this.cmd).Tables[0]; if (table.Rows.Count > 0) { table.Columns.Add("visible"); foreach (DataRow row in table.Rows) { if (this.IsOwner || row["byuid"].ToString().Equals(this.Uid)) { row["visible"] = true; } else { row["visible"] = false; } } table.AcceptChanges(); this.dlComments.DataSource = table; this.dlComments.DataBind(); } } catch (Exception exception) { this.lblMsg.Text = exception.ToString(); } } protected void Page_PreRender(object sender, EventArgs e) { string a = Session["uid"].ToString; if (!base.IsPostBack) { this.fill(); } } public string ArticleID { get { object obj2 = this.ViewState["_ArticleID"]; if (obj2 == null) { return "1"; } return (string)obj2; } set { this.ViewState["_ArticleID"] = value; } } public bool IsOwner { get { return this.IsOwner; } } }
when i try to open a image it says:
System.NullReferenceException: Object reference not set to an instance of an object. at usercontrol_comments.fill() in
d:\inetpub\vhosts\workpage.in\httpdocs\usercontrol\comments.ascx.cs:line 65
line 65 in user control is
this.Uid = base.Session["uid"].ToString();
I think it is losing the session variables.
Plz tell me what i m missing.
thanx in advance...
sessionstate usercontol asp.net Session
amit.saab
Member
18 Points
8 Posts
Re: User control unable to load session variable
Mar 17, 2012 01:29 PM|LINK
Somebody please help me....
markfitzme
Star
14319 Points
2215 Posts
Re: User control unable to load session variable
Mar 17, 2012 03:13 PM|LINK
I don't believe it's loosing the Session variables. The problem is your local variables such as UID are not persisetent. Every time you create a postback to any part of the page (not necessarily clicking on a button in the user control) your UID variable is reset. The simples thing to do is simply make UID a property so that every time you access it, it returns the session variable.
protected string UID
{
get {
if(Session["uid"] != null)
return Session["uid"].ToString();
else
return string.Empty;
}
If you were truly loosing the session variables then you would be getting errors every time you tried to access Session["uid"] because if it was lost, the value would be null and any use of it would have thrown an object reference not found error.