0

I am very new in .Net and not sure how to resolve most of my problems. Here's my issue. I created a form to execute a list of scripts. The data will come from a database. My problem is when I debug I get the NullReferenceException error on this block of code

private void Load_RefreshForm_ScriptMgmt()
{
    try
    {
        SqlCommand ObjCmd = new SqlCommand();
        SqlConnection ObjConn = new SqlConnection();
        this.Ds_Settings1.Tables["Settings_RefreshForm_ScriptMgmt_SelectALL"].Clear();
        ObjConn.ConnectionString = this.MainConnection;
        ObjCmd.CommandType = CommandType.StoredProcedure;
        ObjCmd = new SqlCommand(this.da_LoadScripts.SelectCommand.CommandText.ToString(), ObjConn);
        this.da_LoadScripts.SelectCommand = ObjCmd;
        this.da_LoadScripts.Fill(this.Ds_Settings1);
    }
    catch (Exception exception)
    {
        ProjectData.SetProjectError(exception);
        this.DisplayOnly_ErrorHandler("ERROR LOADING REFRESH SCRIPTS ", exception.Message, MsgBoxStyle.Critical);
        ProjectData.ClearProjectError();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Where is `this.da_LoadScripts.SelectCommand` first set before you overwrite it with `ObjCmd`? If it's null the first time you create and set `ObjCmd`, then you'll get a null exception by trying to access the `CommandText` property. You should be able to determine the exact line where the error happens by debugging your app. – hatchet - done with SOverflow Oct 03 '13 at 19:57
  • 1
    Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 03 '13 at 20:01

2 Answers2

0

You can see which line throw that exception by setting a breakpoint on the first line in the try block and follow the execution.

There are many lines that can throw that exception. this.Ds_Settings1 can be null, this.da_LoadScripts too. If one of these objects is null and you are trying to call a function on it or access a property, you will get that error. Verify if these objects are defined before calling that function.

Francis
  • 367
  • 1
  • 10
0

You can easily track which statement threw this exception by enabling breaking execution in Exceptions window:

Debug > Exceptions... (Ctrl + Alt + E)

and checking the Common Language Runtime Exceptions 'Thrown' checkbox.

As for the exception itself - it's pretty self-explaining - you're trying to use a reference variable which is not assigned to anything (points nowhere).

borkovski
  • 938
  • 8
  • 12