473,883 Members | 1,604 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help on Error "Object reference not set to an instance of an object."

21 New Member
Hi everybody actually i was trying to insert some records in to SQL server through C# Wndows Aplication and during that i face an error "Object reference not set to an instance of an object." and need help from senors please explain me about it and also indicate it in my code.

Here is my code in my Class Named DBHandler!!!

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.SqlClient;
  6. using Program;
  7. using CustomTypes;
  8. using System.Data;
  9. using System.Configuration;
  10.  
  11. namespace InformationDesk
  12. {
  13.     public class DBHandler
  14.     {
  15.  
  16.  
  17.         public void GetAllValues(Person V)
  18.         {
  19.  
  20.             SqlConnection con = new SqlConnection();
  21.             con.ConnectionString = ConfigurationManager.ConnectionStrings["FinalProjectDB"].ConnectionString;
  22.  
  23.  
  24.             SqlCommand com = new SqlCommand();
  25.             com.CommandText = "INSERT INTO Visitors (Name, Email) VALUES (@Name, @Email);";
  26.  
  27.             com.Connection = con;
  28.  
  29.  
  30.             com.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = V.Name;
  31.             com.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = V.Email;
  32.  
  33.             con.Open();
  34.  
  35.             com.ExecuteNonQuery();
  36.  
  37.             con.Close();
  38.  
  39.         }
  40.  
  41.     }
  42.  
  43. }
Person is the class having attrbutes of Person such as Name and Email Address

And i am using GetAllValues function to get values from user in a windows form
after getting values from user assign them to sql command parameters to insert but fcing an error please help me as soon as possible however i am sure that the function GetAllValues need some maintenance in the above code snippte...
Sep 5 '09 #1
5 3842
GaryTexmo
1,501 Recognized Expert Top Contributor
Well, to be honest, your null reference error could be coming from a lot of places. Likely candidates are the parameter you're passing to the method and the connection string itself. I'd suggest throwing a breakpoint in there and stepping through to see which line fails.

In addition, when you do stuff like this it's usually a good idea to throw it in a try/catch block, that way you can handle errors more gracefully and recover, instead of taking down your whole program.
Sep 5 '09 #2
dotnetnovice
21 New Member
Hi Gary thanks for your response but now i have tried another trick with the code now my code look like that.

Expand|Select|Wrap|Line Numbers
  1. public class DBHandler
  2.     {
  3.  
  4.         private const String ConnectionString = @"initial catalog=FinalProjectDB;Data Source=ALIEN\SQLEXPRESS;integrated Security=true;";
  5.  
  6.  
  7.         public void GetAllValues(Person V)
  8.         {
  9.  
  10.             SqlConnection conn = new SqlConnection(ConnectionString);
  11.             SqlCommand objSql = new SqlCommand();
  12.             objSql.Connection = conn;
  13.             objSql.CommandType = CommandType.Text;
  14.             objSql.CommandText = "INSERT INTO Visitors (Name, Email) VALUES (@Name, @Email);";
  15.  
  16.             objSql.Connection = conn;
  17.  
  18.             objSql.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = V.Name;
  19.             objSql.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = V.Email;
  20.  
  21.             conn.Open();
  22.  
  23.             objSql.ExecuteNonQuery();
  24.  
  25.             conn.Close();
  26.  
  27.         }
  28.  
  29.  
  30.  
  31.     }
This code is working well but what i want is just the confirmaton. Is this code safe or not in terms of project crash situations...

i shall wait for your reply...
Sep 6 '09 #3
cloud255
427 Recognized Expert Contributor
No, that code of yours is not safe, look into using TRY CATCH blocks around the DB access. This will allow you to handle exceptions from the DB (server may be offline, validation failure, etc) and allow the user to decide which action to take in response to the exception.
Sep 6 '09 #4
dotnetnovice
21 New Member
Ok I will include Exception Handling in it... Thanks for comments...
Sep 6 '09 #5
tlhintoq
3,525 Recognized Expert Specialist
While its good to not crash, its better resolve the actual problem.
Put a breakpoint at line 10.
Walk through the code line by line (F-10)
Look at the values of each variable/object using the "locals" and "autos" windows. This should let you inspect each variable you are using to see which is still null when you try to use it.

Also setting Visual Studio to break when an exception is thrown, instead of when it goes unhandled will stop it at the point where you null object is trying to be used.
Debug | Exceptions
Click on the 'thrown' checkbox for "Common Language Runtime Exceptions" then run/debug your solution (F5)
Sep 6 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1678
by: Paloma García | last post by:
Dear all, I have created personalized configuration sections in my web project following the instructions described in this page http://msdn.microsoft.com/library/spa/default.asp?url=/library/SPA/cpguide/html/cpcondeclaringcustomconfigurationsections.asp The problem is that I using the same code and I get the error "Object reference not set to an instance of an object" in the line where I try to read the first parameter (in the page...
0
1208
by: Michael Chong | last post by:
I have an (exe) executable program created in VB.NET 2003 that calls to a MFC DLL written in VC++.NET 2003. I always get an error msg "NullReferenceException: Object Reference Not Set to an Instance of an Object" when my exe calls the following codes: in VB.NET Declare Function test Lib "C:\Cyob\IOComm\Debug\IOComm.dll" _ (ByVal a As Long, ByRef b As Integer) As Integer
5
1614
by: Tee | last post by:
Hi, I having a problem with my asp.net project. The project work fine on my own PC, but when I upload it to the server, I got the following error : Object reference not set to an instance of an object I have try to search for the solution using this error message, and I found that a lot of other people have the same problem as the project only work in
18
28765
by: Microsoft | last post by:
When I try this in my code I alwas get an errormessage: "Object reference not set to an instance of an object" Dim g As System.Drawing.Graphics g.DrawString("Test", New Font("Arial", 12, FontStyle.Bold), Brushes.Black, 0, 0) Why is this? Marc
0
2093
by: Martin Widmer | last post by:
Hello again! I have a datagridview control on my form and am using VS.Net 2005. One column is set up as combo box column, and when I try to set the datasource for that combobox column at design time in the properties section of VS, I get the error "object reference not set to instance of an object" and the only option is to click OK. I have not yet tried to set that datasource at runtime, but of course I could do that. But I don't...
2
1867
by: facole | last post by:
I'm new to the .net environment. What I'm trying to do is to have an html page call a .aspx application and pass certain information. I have a field in the html file <input type="text" name="UserName"> I'm call the .aspx program <form name="form1" method="POST" action="/application/test.aspx?">
2
6504
by: =?Utf-8?B?QmFkaXM=?= | last post by:
I'm doing a server side automation(I know it's bad but..) and its working fine locally and when accessing it from a remote machine using web browser is was giving me this error"Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005". so I configured the server using dcomcnfg as described in this link: http://support.microsoft.com/kb/288368/ and know...
3
2342
by: Sarah | last post by:
Hi - Please be gentle. I am quite new to visual basic, but I have been going through tutorials and reading up. I found a code snippet on the internet that I wanted to see if I could re-purpose for a project, but I keep getting the error: "Object reference not set to an instance of an object" for the 7th line of the code below which is: obj.ConvertPage(URL).Save("C:\screencaptest2.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
3
3146
by: shapper | last post by:
Hello, I have the following loop and error message: foreach (Theme theme in Profile.Collaborator.Themes) { ... And I get the following error: Object reference not set to an instance of an object. I know I get this error because Themes is null ... I just don't know how to solve it without needing to do:
0
9781
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11118
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10407
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9564
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7960
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5791
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4209
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3230
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.