User control unable to load session variablehttp://forums.asp.net/t/1780735.aspx/1?User+control+unable+to+load+session+variableSat, 17 Mar 2012 15:13:47 -040017807354882027http://forums.asp.net/p/1780735/4882027.aspx/1?User+control+unable+to+load+session+variableUser control unable to load session variable <p>Hey all,</p> <p>m having this problem with my site...</p> <p>Its kinna social networking site. On login the user id gets loaded as session variable &quot;uid&quot; and its getting passed to all the pages fine</p> <p>I have defined a user control to load the comments and likes of a particular image uploaded by user</p> <p>here is the code for image.aspx:</p> <pre class="prettyprint">&lt;%@ Page Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeFile=&quot;Image.aspx.cs&quot; Inherits=&quot;Image&quot; %&gt; &lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt; &lt;%@ Register Src=&quot;~/usercontrol/comments.ascx&quot; TagName=&quot;comments&quot; TagPrefix=&quot;UC&quot; %&gt; &lt;%@ Register Src=&quot;~/usercontrol/Likes.ascx&quot; TagName=&quot;likes&quot; TagPrefix=&quot;UC&quot; %&gt; &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt; &lt;head id=&quot;Head1&quot; runat=&quot;server&quot;&gt; &lt;title&gt;&lt;/title&gt; &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;!-- Google Font and style definitions --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;http://fonts.googleapis.com/css?family=PT&#43;Sans:regular,bold&quot; /&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot; /&gt; &lt;!-- include the skins (change to dark if you like) --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/light/theme.css&quot; id=&quot;themestyle&quot; /&gt; &lt;!-- Use Google CDN for jQuery and jQuery UI --&gt; &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;style&gt;//style definations here &lt;/style&gt; &lt;/head&gt; &lt;body style=&quot;text-align: center&quot;&gt; &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt; &lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot;&gt; &lt;/asp:ScriptManager&gt; &lt;asp:Image ID=&quot;imgImage&quot; runat=&quot;server&quot; CssClass=&quot;myimage&quot; /&gt; &lt;br /&gt; &lt;asp:Label ID=&quot;lblDescription&quot; runat=&quot;server&quot; Text=&quot;&quot;&gt;&lt;/asp:Label&gt; &lt;br /&gt; &lt;table style=&quot;margin: 0px&quot;&gt; &lt;tr&gt; &lt;td&gt; &lt;%--likes usercontrol here--%&gt; &lt;UC:likes ID=&quot;likes&quot; runat=&quot;server&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;div align=&quot;right&quot; style=&quot;font-size: 15px; font-weight: bolder; padding-right: 40px&quot;&gt; &lt;span id=&quot;lblCurrent&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;%-- comments usercontrol here--%&gt; &lt;UC:comments ID=&quot;comments&quot; runat=&quot;server&quot; IsOwner=&quot;false&quot; /&gt; &lt;/form&gt; &lt;div runat=&quot;server&quot; id=&quot;divRestricted&quot;&gt; This Content is only available to certain Users. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</pre> <p>image.aspx.cs is:</p> <pre class="prettyprint"> 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 &gt; 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) &amp;&amp; (flag2 || flag))) || ((num == 2) &amp;&amp; flag)) { this.imgImage.ImageUrl = "api/image.ashx?width=640&amp;height=480&amp;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(); } } } </pre> <p>User control comments.ascx.cs is:</p> <pre class="prettyprint"> 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", "&lt;br /&gt;").Replace("\n", "&lt;br /&gt;").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 &gt; 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; } } } <br /><br /> </pre> <p>when i try to open a image it says:<br> System.NullReferenceException: Object reference not set to an instance of an object. at usercontrol_comments.fill() in<br> d:\inetpub\vhosts\workpage.in\httpdocs\usercontrol\comments.ascx.cs:line 65</p> <p></p> <p>line 65 in user control is</p> <p>this.Uid = base.Session[&quot;uid&quot;].ToString();</p> <p></p> <p>I think it is losing the session variables. </p> <p>Plz tell me what i m missing.</p> <p>thanx in advance... </p> 2012-03-15T15:00:52-04:004885280http://forums.asp.net/p/1780735/4885280.aspx/1?Re+User+control+unable+to+load+session+variableRe: User control unable to load session variable <p>Somebody please help me....</p> 2012-03-17T13:29:26-04:004885356http://forums.asp.net/p/1780735/4885356.aspx/1?Re+User+control+unable+to+load+session+variableRe: User control unable to load session variable <p>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.</p> <p>protected string UID<br> {<br> &nbsp;&nbsp;&nbsp;&nbsp; get {<br> if(Session[&quot;uid&quot;] != null)<br> &nbsp;&nbsp;&nbsp; return &nbsp;<span class="typ">Session</span><span class="pun">[</span><span class="str">&quot;uid&quot;</span><span class="pun">].</span><span class="typ">ToString();<br> else<br> &nbsp;&nbsp;&nbsp;&nbsp;return string.Empty;<br> }</span><span class="pln"><br> </span></p> <p><span class="pln">If you were truly loosing the session variables then you would be getting errors every time you tried to access Session[&quot;uid&quot;] because if it was lost, the value would be null and any use of it would have thrown an object reference not found error.</span></p> <p><span class="pln"></span></p> 2012-03-17T15:13:47-04:00