473,547 Members | 2,532 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

System.NullRefe renceException - Object reference not set to an instance of an object

I am getting this exception error which is driving me nuts.
System.NullRefe renceException - Object reference not set to an instance
of an object

If I comment this line, I don't get any errors:
string Total_Dollar_Am ount = GetTotal(sql,"t est");

namespace SalesReport
{
/// <summary>
/// Summary description for SalesReport.
/// </summary>
public class SalesReport : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Butt on Button1;

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
}

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

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Button1.Cl ick += new System.EventHan dler(this.Butto n1_Click);
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

private ArrayList GetRowsArray()
{
ArrayList Ar = new ArrayList();
SqlConnection Conn = Common.GetConne ction("sonny");
string sql = "SELECT * from Sn_SalesReport" ;
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connect ion.Open();
SqlDataReader r = Command.Execute Reader();
while (r.Read())
{
string sqlstatement = r["sqlstateme nt"].ToString();
Ar.Add(sqlstate ment);
Response.Write( sqlstatement+"< br>");
}
r.Close();
Conn.Close();
return Ar;
}
private void Button1_Click(o bject sender, System.EventArg s e)
{
ArrayList Ar = GetRowsArray();
// create the Thread array
Thread[] t = new Thread[ Ar.Count ];
int lIdx;
ProcessSQL sr;

for ( lIdx = 0; lIdx < Ar.Count; lIdx ++ )
{
sr = new ProcessSQL(Ar[lIdx].ToString());
t[lIdx] = new Thread( new ThreadStart( sr.UpdateSalesR eport ) );
t[lIdx].Start();
}

for ( lIdx = 0; lIdx < Ar.Count; lIdx ++ )
{
// waiting for all the Threads to finish.
t[lIdx].Join();
}

}
}

public class ProcessSQL
{
private string sql;
public ProcessSQL (string sql)
{
this.sql = sql;
}

public void UpdateSalesRepo rt()
{
try
{
string Total_Dollar_Am ount = GetTotal(sql,"t est");
}
catch(Exception ex)
{
HttpContext.Cur rent.Response.W rite("Error#### ####: "+ex.Messag e);
}
}

public string GetTotal(string sql, string database)
{
sql = "Select reportname from SN_SalesReport" ;
string result = string.Empty;
try
{
SqlConnection Conn = Common.GetConne ction(database) ;
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connect ion.Open();
SqlDataReader r = Command.Execute Reader();
if(r.Read())
{
// gets total
result = r.GetString(0);
}
r.Close();
if (Conn!=null)
{
Conn.Close();
}

}
catch(Exception ex)
{
HttpContext.Cur rent.Response.W rite("Error#### ####: "+ex.Messag e);
}
return result;
}
}


}

Nov 17 '05 #1
17 9665
Rodusa <rc**********@y ahoo.com> wrote:
I am getting this exception error which is driving me nuts.
System.NullRefe renceException - Object reference not set to an instance
of an object

If I comment this line, I don't get any errors:
string Total_Dollar_Am ount = GetTotal(sql,"t est");


Rather than printing out just the message, print out the full stack
trace. That way you should be able to see which line of your code is
throwing the exception.

Note that to make your code more robust you should be using "using"
statements for your connection/command/data reader, rather than calling
Close directly. (Currently if an exception is thrown, the connection
isn't closed.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2


*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it? Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.

Thank you

Rodrigo Lueneberg

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #4
Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it? Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.

Thank you

Rodrigo Lueneberg

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Rodrigo Lueneberg <ro************ **@hotmail.com> wrote:
Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it?
Well, you're currently printing out ex.Message. Instead, print out
ex.ToString().
Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.


You shouldn't be trying to use the same connection from multiple
threads - if you're doing that, that's a mistake. You can, however, use
different connections from different threads.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
I tried ex.ToString(), but the exception is being thrown by Visual
Studio, before it reaches the application. And when I try to debug, it
says "There is no source code available for the current location".
That's is why I am lost. I don't have any way to figure out.
Regarding, the connections, I heard about threadpool? Is that what you
mean? I had the wrong thought that GetTotal method had a privated
instance of Conn and it should automatically create different calls in
memory, causing no problems with opening and closing different
connections when using threads. Howevever, if this is not what you are
thinking, how can I create multiple instance Conn in this scenario?

Nov 17 '05 #7
Jon, I did implement the "using as you said". It doesn't seem to be a
connection problem because when I comment the datareader block the page
runs with no problem. It looks like it is something to do with the
datareader. The problem is I can't create a new instance of the
datareader.

public string GetTotal(string sql, string database)
{

sql = "Select reportname from SN_SalesReport" ;
string result = string.Empty;
try
{
using (SqlConnection Conn = new
SqlConnection(C onfigurationSet tings.AppSettin gs[database]))
{
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connect ion.Open();
//using(SqlDataRe ader r = Command.Execute Reader())
{
// if(r.Read())
// {
// gets total
// result = r.GetString(0);
// }
// r.Close();
// if (Conn!=null)
// {
// Conn.Close();
// }
}
}

}
catch(Exception ex)
{
HttpContext.Cur rent.Response.W rite("Error#### ####:
"+ex.ToString() );
}
return result;
}

Nov 17 '05 #8
Rodusa <rc**********@y ahoo.com> wrote:
I tried ex.ToString(), but the exception is being thrown by Visual
Studio, before it reaches the application. And when I try to debug, it
says "There is no source code available for the current location".
That's is why I am lost. I don't have any way to figure out.
Regarding, the connections, I heard about threadpool? Is that what you
mean?
No, not quite.
I had the wrong thought that GetTotal method had a privated
instance of Conn and it should automatically create different calls in
memory, causing no problems with opening and closing different
connections when using threads. Howevever, if this is not what you are
thinking, how can I create multiple instance Conn in this scenario?


I suspect the problem you're seeing isn't related to not using a using
statement - that was just a separate bug in your code which was worth
pointing out before it hit you.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Rodusa <rc**********@y ahoo.com> wrote:
Jon, I did implement the "using as you said". It doesn't seem to be a
connection problem because when I comment the datareader block the page
runs with no problem. It looks like it is something to do with the
datareader. The problem is I can't create a new instance of the
datareader.


What do you mean by "you can't create a new instance of the
datareader"? What happens when you try?

Note that the SqlCommand should be in a using block too, for
preference. (It probably doesn't matter, at least not at the moment,
but it's good practice.)

Also note that as you've got a using block, you don't need to call
Close on the connection or the reader - it disposes of them
automatically.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

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

Similar topics

3
9110
by: Terrence | last post by:
I am doing some of the C# walkthroughs to transition from VB to C#. When I try to execute static void Main() { Aplication.Run(new Form1()) } I raise a 'System.NullReferenceException" in system.windows.forms.dll
7
8092
by: mike p. | last post by:
I have a docbook xml file, and am using standard docbook 1.61.3 xsl stylesheets to do xhtml transform. Transform works fine when using MSXML. When I try to do the following using asp.net 1.1: private void Page_Load(object sender, System.EventArgs e) { // load content XslTransform trans = new XslTransform();
0
9754
by: muralidharan | last post by:
WebForm1.aspx Code: <%@ Register TagPrefix="ComponentArt" Namespace="ComponentArt.Web.UI" Assembly="ComponentArt.Web.UI" %> <ComponentArt:TreeView id="TreeView1" Height="520" AutoPostBackOnNodeMove="false" DragAndDropEnabled="true" NodeEditingEnabled="False" KeyboardEnabled="true" CssClass="TreeView" NodeCssClass="TreeNode"...
5
4015
by: Vitling | last post by:
For no apparent reason, a NullReference exception is thrown in system.dll (System.Net.Sockets.OverlappedAsyncResult.CompletionPortCallback). Since I only get a disassembly from Visual Studio, it is almost impossible to figure out what causes this. I've tried adding: AppDomain.CurrentDomain.UnhandledException += new...
2
7791
by: Raed Sawalha | last post by:
i have a windows form(Main) with listview, when click an item in listview i open other window form (Sub) which generate the selected item from parent window in as treeview items when click any item in treeview i display the content item in axWebBrowser, i close the sub form normally when i close the main the following error is generated An...
1
4083
by: msnews.microsoft.com | last post by:
I'm trying to fill an array of objects but when I add the first object I get a NullReferenceException. ---------------------------------------------------------------------------- ------------------------------------------- Public Class TestClass Public NextSubIndex As Integer = 1 Public arrTestSubClass() As TestSubClass
4
5085
by: Terry Mulvany | last post by:
I have a 'BasePage' (BasePage.cs) derived from System.Web.UI.Page that all my pages inherit from. I need to set some properties (either in the OnInit or constructor) based on a potential Request.Cookie or a name/value pair in Request.QueryString. But I am getting a 'System.NullReferenceException: Object reference not set to an instance of...
2
2731
by: sxiao | last post by:
Hi, there I got a NullReferenceException when there are more than one users trying to open the same page at the same time. The senerio is: Two users logged into the web application using the Windows domain user account and tried to open the same page which has the databasde query code. When the two user tried to open the same page at the...
3
2435
by: Brano | last post by:
HI all, I have a problem i have a web application that was working fine and this morning when i run it and click on a button that does Reponse.Redirect to a page i get this error : Server Error in '/IPFWEb_6' Application. -------------------------------------------------------------------------------- Object reference not set to an...
6
22203
by: William Mild | last post by:
I must be getting brain fried. I can't see the error. Create a new web form with the following code begind: Public Class test Inherits System.Web.UI.Page Public Class ReportCardData Public Structure Attend Dim DaysTardy As Double
0
7510
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7437
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7703
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7947
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7463
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6032
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5362
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3473
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.