The C# team posts answers to common questions and describes new language features
The code is trying to access a member of a reference type variable that is set to null.
Given the following class, let's examine some code that could be in the Main method:
using System; class Foo { static void Main() { // foo has not been instantiated Foo foo = null; // implementation to be discussed... } public int BarProperty { get { return 0; } } public string BarMethod() { return null; } }
Looking at Main, notice that foo is set to null. Your situation will not be this explicit because the variable you are trying to use could be a class field, parameter, or local variable that was once instantiated but was subseqently set to null. Given that foo is null, the following code will throw a NullReferenceException:
try { // foo is null, and you can't call // BarProperty on null. int resultBad = foo.BarProperty; } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't read BarProperty, foo is null.\n" + nre.Message); }
Since foo is null, you can not use its members. This was a property, but the following code demonstrates calling a method:
try { // foo is null, and you can't call // BarMethod on null. foo.BarMethod(); } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't call BarMethod(), foo is null.\n" + nre.Message); }
The code above throws a NullReferenceException because foo is still null. It doesn't matter that the first call was a property and the second is a method - they are both members of the type.
Now, to fix this problem, you must ensure that foo is instantiated before it is used. The following code instantiates foo and the previous problems are solved:
// now we have an instance foo = new Foo(); // works fine int resultGood = foo.BarProperty;
Since foo now refers to a valid instance, the code can call any of its members. This was easier than many null reference problems. Sometimes you have multiple levels of indirection, leaving you with a scenario you didn't expect. Assuming that foo now references an object, there is still a problem with the following code:
try { // still breaks because BarMethod() returned // null and you can't call Trim() on null. foo.BarMethod().Trim(); } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't call Trim(), BarMethod() returns null.\n" + nre.Message); }
The problem occurs in the code above because BarMethod returned null, which means that the code is trying to call the Trim method on a string reference that is set to null.
The proper way to fix this problem is to debug BarMethod to find out why it returned null. That assumes BarMethod is not supposed to return null. If, in your application, it made sense for BarMethod to sometimes return null, then you would have to check the return value of BarMethod before you called any members of the return value.
[Author: Joe Mayo]
I always meet this exception:)
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web .Configuration ;
using System.Data .SqlClient ;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
public partial class Default2 : System.Web.UI.Page
{
public string connection = WebConfigurationManager.AppSettings["pubs1"].ToString();
SqlConnection cnew = new SqlConnection(ConfigurationManager.AppSettings["pubs1"].ToString());// new SqlConnection();
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
bindgrid();
}
void bindgrid()
List <company> item=new List <company>(5);
for(int i=0;i<5;i++)
company c=new company ();
item.Add (c);
GridView1.DataSource = item;
GridView1.DataBind();
protected void clearButton_Click(object sender, EventArgs e)
void beginadd()
//SqlConnection cnew = new SqlConnection(connection);
//SqlCommand cmd = new SqlCommand();
cnew.Open();
SqlTransaction tran = cnew.BeginTransaction();
cmd.Connection = cnew;
cmd.Transaction = tran;
cmd.CommandText = "insert into msm_company(comp_id,comp_name)values (@companyid,@companyName";
SqlParameter p1 = new SqlParameter("@companyid", SqlDbType.VarChar);
SqlParameter p2 = new SqlParameter("@companyName", SqlDbType.VarChar);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
//cnew.Close();
void addcustomer(string companyid,string companyname)
try
//cnew.Open();
cmd.Parameters[0].Value = companyid;
cmd.Parameters[1].Value = companyname;
cmd.ExecuteNonQuery();
catch
cmd.Transaction .Rollback ();
void completeadd()
//cmd.Transaction.Commit();
Label1.Text = "record added successfully";
catch (Exception ex)
Label1.Text = "error inserting record";
Label1.Text += ex.Message;
finally
cnew.Close();
protected void saveButton_Click(object sender, EventArgs e)
beginadd();
foreach (GridViewRow row in GridView1.Rows)
if (row.RowType == DataControlRowType.DataRow)
string companyid = ((TextBox)row.FindControl("textbox1")).Text;
string companyname = ((TextBox)row.FindControl("textbox2")).Text;
if (companyid != "")
addcustomer(companyid, companyname);
completeadd();
this is my code.Why do I get the error "Object reference not set to an instance of an object"?
So............what do I have to do in order not to receive the message prompt. How do I fix it. If I can bypass this without having to consult our IT guys it will be awesome
TX
Unbelievable. So for those who found this page via Google, the best place to get the answer to your question is here:
en.csharp-online.net/CSharp_FAQ:_What_does_Object_reference_not_set_to_an_instance_of_an_object_mean
I really enjoy how the first responder sarcastically responds in know-it-all fashion without explaining anything to anyone, then his friends chime in and say it comes up a lot, then 7 years of the same question go by and NO ONE EVER ANSWERS IT!
Sheesh!
[NullReferenceException: Object reference not set to an instance of an object.]
mssqlonly_clone.Web.UI.PlayerSettings.btn_show_Click(Object sender, EventArgs e) +166
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:
1. Add a "Debug=true" directive at the top of the file that generated the error. Example:
<%@ Page Language="C#" Debug="true" %>
or:
2) Add the following section to the configuration file of your application:
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.
Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.
Stack Trace:
Admin_passward_login.Button1_Click(Object sender, EventArgs e) +205
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565