Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
I'm working on win apps in c# and VS using Sql server 2008.
While I'm debugging the code the object reference not set to an instance of object
error occurring..I could not know what to to do and where is issue...please Help me out
C#
public void autoinc()
{
   try
   {

      var connectionString = ConfigurationManager.ConnectionStrings["smallprojects"].ConnectionString;//this is my conncetion strin here I'm getting error and here smallprojects is my ddatabase
      SqlConnection cn = new SqlConnection(connectionString);
      cn.Open();
      SqlCommand command = new SqlCommand("Select isnull(max(S_No),0) from salary", cn);//here salary is my database table and in that table there is column name S_NO
                
      //cn.Open();
      object result = command.ExecuteScalar();

      txtsno.Text = (int.Parse(result.ToString()) + 1).ToString();
      cn.Close();
                
   }
   catch (Exception e1)
   {
      MessageBox.Show(e1.Message);
   }
}

This my configuration file is followed .
C#
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="smallprojects"
    connectionString="Data Source=.;Initial Catalog=smallprojects;Integrated Security=True "/> 
  </connectionStrings>
</configuration>
Posted
Updated 6-Nov-14 6:13am
v3
Comments
Sergey Alexandrovich Kryukov 6-Nov-14 2:09am    
In what line? Did you use the debugger?
—SA
n shiva Ram 6-Nov-14 2:11am    
var connectionString = ConfigurationManager.ConnectionStrings["smallprojects"].ConnectionString;at this line Im getting error and I used debugger also
Sergey Alexandrovich Kryukov 6-Nov-14 10:44am    
Did you see that ConfigurationManager.ConnectionStrings["smallprojects"] is null?
You could see it under the debugger.
If so, how could you dereference it?
—SA
Maciej Los 6-Nov-14 2:14am    
Data Source=.?
n shiva Ram 6-Nov-14 2:15am    
what do you mean? do i use "?" mark at data source?

In the last couple of days there are many "object not set" questions and it is one of the easist one to find and solve. Learn to use break points.

In VS press F9 while on the line and breakpoint will be set. Run Debug configuration and you'll be stopped at that point.

Second: there is Watch window
Set one in that line of code and send parts of the line into Watch window. You can find the watch window under View -> Other windows or under Debug -> Windows (never sure which one :) )

There you can write expressions to observe during execution of your program (as long as you're stopped at the breakpoint.

If this helps, please take time to accept the solution. Thank you.
 
Share this answer
 
v2
Hi shiv ram,
In your case..
Please first check the connection by writing like this.
C#
var connectionString = "Data Source=.;Initial Catalog=smallprojects;Integrated Security=True "

1. check for the datasource instance name in your SQL Server Management Studio. It may be like ".\SQLExpress".
2. put a break point at the point and then debug.
 
Share this answer
 
v2
Comments
n shiva Ram 6-Nov-14 4:34am    
It is working without config file but i want to work on config file
Jineesh TR 6-Nov-14 4:37am    
Did you checked the connectionstring by puting a break point? What is your error?
n shiva Ram 6-Nov-14 4:44am    
by placing a break pint I get object reference not set to an instance of object error
Jineesh TR 6-Nov-14 5:09am    
Hi Shiv Ram put a break point at
var connectionString = ConfigurationManager.ConnectionStrings["smallprojects"].ConnectionString;
if the connection string at this point is null, then
1. select project porperties, select tab settings, then check your connection string there.
2. Or you try for reading the xml file as string then use this string as your connection string. refer http://csharp.net-informations.com/xml/how-to-read-xml.htm
Please see my comment to the solution. You got a null from a property which is supposed to return a reference object (don't use hard-coded string constants, by the way), and tried to dereference it by taking some instance members of it. You used the debuggers, so what? You need to be able to find such things by yourself.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Good luck,
—SA
 
Share this answer
 
Try Using
C#
string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["smallprojects"].ToString();
 
Share this answer
 
Comments
n shiva Ram 6-Nov-14 4:47am    
tried ur line but throwing an error saying configuration.sqlconnection error
member86215483 20-Nov-14 7:34am    
Can u tell me at which line are you getting error.? Also give a detailed exception , if any

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900