Search code examples
c#asp.netcustom-server-controlshtmltextwriter

Page.Session not set to an instance


I'm having trouble understanding how Page.Request.QueryString and Page.Session works. How would I assign a name to this string

protected override void Render(HtmlTextWriter output)
    {

        SqlConnection sqlConnection = new SqlConnection(connectionString);
        SqlCommand sqlCommand = new SqlCommand();
        StringBuilder stringBuilder1 = new StringBuilder();
        StringBuilder stringBuilder2 = new StringBuilder();
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "proc_UserBids";
        sqlCommand.CommandTimeout = 1000;
        string str = this.Page.Request.QueryString["name"] == null ? this.Page.Session["name"].ToString() : ((object)this.Page.Request.QueryString["name"]).ToString();
        if (!(str == ""))
        {
      //Do Something
       }
}

The error I'm getting is:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

 string str = this.Page.Request.QueryString["name"] == null ? this.Page.Session["name"].ToString() : ((object)this.Page.Request.QueryString["name"]).ToString();

Solution

  • You must set some value to session called name.

    Example (vb.net) :

    Session.Add("name","some string")
    

    Then You can use this Session("name") in any page.

    For example in some other page : Dim str As String = Session("name")

    If You want pass some value using QueryString, from one to another page then use below code. Example : deafult.aspx

    Response.Redirect("otherpage.aspx?name=Some string")
    

    otherpage.aspx (code behind) :

    Request.QueryString("name")
    

    I hope so this is what You need.