472,354 Members | 2,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,354 software developers and data experts.

Problem maintaining dataset in session variable

I have a web interface where the user types in ID's one at a time. After an
ID is typed in, a button is clicked and the button click event has code that
does a query and returns a data reader and then appends the data to a
dataset that is built in the Page_Load code in the if(!isPostBack) block.
When I try to add a row in the button click event code I get an error saying
that "Object reference not set to an instance of an object". I'm saving the
dataset in a Session object and then restoring it in the else clause of the
if(!isPostBack) block. I've pasted code below, please help. I'm relatively
new at asp.net development but have lots of asp and ado experience.

Thanks,

John Holmes
--------------------------------- code ----------------------------------
using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using ConnectionLibrary;

using System.Data.SqlClient;

namespace Affidavits

{

/// <summary>

/// Summary description for WebForm1.

/// </summary>

public class WebForm1 : System.Web.UI.Page

{

protected System.Web.UI.WebControls.TextBox TextBox1;

protected System.Web.UI.WebControls.TextBox TextBox2;

protected System.Web.UI.WebControls.DataGrid DataGrid1;

protected System.Web.UI.HtmlControls.HtmlButton btnAddParcel;

public DataSet dsAssessorData;
private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if(!IsPostBack)

{

// create a dataset

BuildDataSet();

// save as session variable

Session["dsAssr"] = dsAssessorData;

}

else

{

DataSet dsAssessorData = new DataSet("Parcels");

dsAssessorData = (DataSet) Session["dsAssr"];

}

}

private void BuildDataSet()

{

DataTable dtParcels = new DataTable("tabParcels");

// add columns

DataColumn dcID = new DataColumn("ParcelID",typeof(string));

dcID.Unique = true;

dcID.AllowDBNull = false;

dtParcels.Columns.Add(dcID);
DataColumn dcAssessedValue = new DataColumn("Assessed", typeof(int));

dcAssessedValue.AllowDBNull = false;

dtParcels.Columns.Add(dcAssessedValue);

DataColumn dcAddress = new DataColumn("Address", typeof(string));

dcAddress.AllowDBNull = false;

dtParcels.Columns.Add(dcAddress);
DataSet dsAssessorData = new DataSet("Parcels");

dsAssessorData.Tables.Add(dtParcels);

// add a test row

DataRow rowNew = dsAssessorData.Tables[0].NewRow();

rowNew["ParcelID"] = "P34031";

rowNew["Assessed"] = "255000";

rowNew["Address"] = "88493" + " " + "Nowhere Road" +

", " + "Everywhere, WA 98834";

dsAssessorData.Tables[0].Rows.Add(rowNew);

DataGrid1.DataSource = dsAssessorData.Tables[0];

DataGrid1.DataBind();

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}
/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.btnAddParcel.ServerClick += new
System.EventHandler(this.btnAddParcel_ServerClick) ;

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

//************* error occurs in this click event

private void btnAddParcel_ServerClick(object sender, System.EventArgs e)

{

// connect to database and retrieve data

string strCn =
SCConnection.GetConnectionString(SCConnection.Asse ssor,false);

string strSql = "select * from ExciseAffidavitView where [parcel number] =
'" +

TextBox2.Text + "'";

SqlConnection cn = new SqlConnection(strCn);

cn.Open();

SqlCommand cmdGetAssrData = new SqlCommand(strSql,cn);

SqlDataReader drAssessor = cmdGetAssrData.ExecuteReader();

// I tried adding this code, but it didn't help

//DataSet dsAssessorData = new DataSet("Parcels");

//dsAssessorData = (DataSet) Session["dsAssr"];

while(drAssessor.Read())

{

//*************** error occurs on the following line

DataRow rowNew = dsAssessorData.Tables[0].NewRow();

rowNew["ParcelID"] = drAssessor.GetString(0);

rowNew["Assessed"] = drAssessor.GetString(15);

rowNew["Address"] = drAssessor.GetString(3) + " " + drAssessor.GetString(4)
+

", " + drAssessor.GetString(5);

dsAssessorData.Tables[0].Rows.Add(rowNew);

DataGrid1.DataSource = dsAssessorData.Tables[0];

DataGrid1.DataBind();

}

// update session variable

Session["dsAssr"] = dsAssessorData;
TextBox1.Text += TextBox2.Text;

TextBox2.Text = "";

cn.Close();
}
}

}

Nov 18 '05 #1
2 3313
Hi John Holmes,
Thank you for using Microsoft Newsgroup Services. Based on your desciption,
you are dealing a ASP.NET web page ,the page loaded a DataSet on first
request and stored it into Session, then in the later request(such as
button click post back.), retrieve the dataset from the Session and do some
operation(such as add a row). However, you encountered some errors when run
the page, seems the dataset isn't set to the Session. Please correct me if
my understanding it not quite exact.

After reading the page's code you provided, I found that there is something
incorrect in it:
you define a DataSet in the page class as a public member as below:
public DataSet dsAssessorData;

however, in the BuildDataSet function, you defined another function scope
local DataSet vairable:
private void BuildDataSet()

{

.........................
DataSet dsAssessorData = new DataSet("Parcels");

..........................

}

Also, in the Page_Load , you code like this:
..................
if(!IsPostBack)

{
// create a dataset
BuildDataSet();

// save as session variable
Session["dsAssr"] = dsAssessorData;
}
.......................

the "dsAssessorData" you set to the Session["dsAssr"] is the public class
member DataSet, not the local DataSet variable,
So it is set to "null" which caused the "Null reference" error. You may
set the new DataSet to the public class membe DataSet in BuildDataSet()
function.

In addtion, to make it clear, I've written a simple page showing how to
create a DataSet at first request and then store in Session for later
retrieving, here is the source:

---------------ASPX PAGE ---------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>SessionDataSet</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td>
<asp:DataGrid id="dgSession" runat="server"></asp:DataGrid>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Button id="btnAdd" runat="server" Text="AddRow"></asp:Button>
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</HTML>

--------------------------CODE BIND
ASPX.CS-------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace NewWebApp
{
/// <summary>
/// Summary description for SessionDataSet.
/// </summary>
public class SessionDataSet : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgSession;
protected System.Web.UI.WebControls.Button btnAdd;
protected DataSet dsTemp = null;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!IsPostBack)
{
dsTemp = GetDataSet();
dgSession.DataSource = dsTemp;
dgSession.DataBind();
Session["DATASET"] = dsTemp;
}
else
{
dsTemp = (DataSet)Session["DATASET"];
}

}

protected DataSet GetDataSet()
{
DataSet ds = new DataSet("dsSession");
DataTable tb = new DataTable("tbSession");

tb.Columns.Add("id");
tb.Columns.Add("name");
tb.Columns.Add("email");

for(int i=0;i<20;i++)
{
DataRow newrow = tb.NewRow();
newrow["id"] = i.ToString();
newrow["name"] = "name" + i.ToString();
newrow["email"] = "email" + i.ToString();

tb.Rows.Add(newrow);
}

ds.Tables.Add(tb);

return ds;
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnAdd_Click(object sender, System.EventArgs e)
{
DataTable tb = dsTemp.Tables["tbSession"];
DataRow newrow = tb.NewRow();

Random rnd = new Random();
int rval = rnd.Next();

newrow["id"] = rval.ToString();
newrow["name"] = "name" + rval.ToString();
newrow["email"] = "email" + rval.ToString();

tb.Rows.Add(newrow);

dgSession.DataSource = dsTemp;
dgSession.DataBind();

}
}
}
Please try the preceding suggestion and let me know if you have any
question on it.
Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #2
Thanks, this helped ... john

"Steven Cheng[MSFT]" <v-******@online.microsoft.com> wrote in message
news:Lh**************@cpmsftngxa07.phx.gbl...
Hi John Holmes,
Thank you for using Microsoft Newsgroup Services. Based on your desciption, you are dealing a ASP.NET web page ,the page loaded a DataSet on first
request and stored it into Session, then in the later request(such as
button click post back.), retrieve the dataset from the Session and do some operation(such as add a row). However, you encountered some errors when run the page, seems the dataset isn't set to the Session. Please correct me if
my understanding it not quite exact.

After reading the page's code you provided, I found that there is something incorrect in it:
you define a DataSet in the page class as a public member as below:
public DataSet dsAssessorData;

however, in the BuildDataSet function, you defined another function scope
local DataSet vairable:
private void BuildDataSet()

{

........................
DataSet dsAssessorData = new DataSet("Parcels");

.........................

}

Also, in the Page_Load , you code like this:
.................
if(!IsPostBack)

{
// create a dataset
BuildDataSet();

// save as session variable
Session["dsAssr"] = dsAssessorData;
}
......................

the "dsAssessorData" you set to the Session["dsAssr"] is the public class
member DataSet, not the local DataSet variable,
So it is set to "null" which caused the "Null reference" error. You may
set the new DataSet to the public class membe DataSet in BuildDataSet()
function.

In addtion, to make it clear, I've written a simple page showing how to
create a DataSet at first request and then store in Session for later
retrieving, here is the source:

---------------ASPX PAGE ---------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>SessionDataSet</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td>
<asp:DataGrid id="dgSession" runat="server"></asp:DataGrid>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Button id="btnAdd" runat="server" Text="AddRow"></asp:Button>
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</HTML>

--------------------------CODE BIND
ASPX.CS-------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace NewWebApp
{
/// <summary>
/// Summary description for SessionDataSet.
/// </summary>
public class SessionDataSet : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgSession;
protected System.Web.UI.WebControls.Button btnAdd;
protected DataSet dsTemp = null;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!IsPostBack)
{
dsTemp = GetDataSet();
dgSession.DataSource = dsTemp;
dgSession.DataBind();
Session["DATASET"] = dsTemp;
}
else
{
dsTemp = (DataSet)Session["DATASET"];
}

}

protected DataSet GetDataSet()
{
DataSet ds = new DataSet("dsSession");
DataTable tb = new DataTable("tbSession");

tb.Columns.Add("id");
tb.Columns.Add("name");
tb.Columns.Add("email");

for(int i=0;i<20;i++)
{
DataRow newrow = tb.NewRow();
newrow["id"] = i.ToString();
newrow["name"] = "name" + i.ToString();
newrow["email"] = "email" + i.ToString();

tb.Rows.Add(newrow);
}

ds.Tables.Add(tb);

return ds;
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnAdd_Click(object sender, System.EventArgs e)
{
DataTable tb = dsTemp.Tables["tbSession"];
DataRow newrow = tb.NewRow();

Random rnd = new Random();
int rval = rnd.Next();

newrow["id"] = rval.ToString();
newrow["name"] = "name" + rval.ToString();
newrow["email"] = "email" + rval.ToString();

tb.Rows.Add(newrow);

dgSession.DataSource = dsTemp;
dgSession.DataBind();

}
}
}
Please try the preceding suggestion and let me know if you have any
question on it.
Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: John Holmes | last post by:
I have a web interface where the user types in ID's one at a time. After an ID is typed in, a button is clicked and the button click event has code that does a query and returns a data reader and...
7
by: Billy Jacobs | last post by:
I am having a problem with my session variable being set to Null for no apparent reason. I am declaring it like the following when the user logs in. dim objUserInfo as new clsUserInfo 'Set...
5
by: Newton | last post by:
Hi, I got here the following problem. I am programming web application for examing students. After student will log on I need to keep his ID, Privileges, Login, Password for manipulating with...
1
by: Phanidhar | last post by:
Hi We are developing an ASP.NET application is being accessed by multiple users simultaneously. We are facing a problem in retrieving the ASP.NET session of the logged on users correctly. Let me...
1
by: Nathan Sokalski | last post by:
I am trying to increment the Session variable at certain points in my code, but it will not work. The initial value assigned to it is always the one that is displayed. Here is the code used to...
3
by: Shapper | last post by:
Hello, How to determine if a Session Variable exists? In Page_Load I need to check is Session("MyVar") Exists. If it doesn't exist then I created it and give it a value: Session("myVar") =...
6
by: Dirc Khan-Evans | last post by:
I have a problem with a Session variable that dissapears after a postback of one of my pages. This only happens on WIn 2003 servers.. it is fine on my XP dev box. This page opens in another...
5
by: garks | last post by:
I am the newbie in php I have a problem about the session variable When I create the session and session variable, the variable is set in page 1, but in page 2 the variable is unset and I don't...
2
by: RoFaR | last post by:
I have a dataset, dinamically I create a table and fill them with data, then I add the table to the dataset, The dataset is stored in a session variable. Later When I access the dataset from the...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made but the http to https rule only works for...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.