0

need your help, I am following an online tutorial of creating an SQL database

http://www.homeandlearn.co.uk/csharp/csharp_s12p9.html

I have followed the code provided to the dot, but i have am en-countering an error where i keep get the object reference is of set of an instance of an object in C#

The code that visual studio is flagging up is

cb.DataAdapter.Update(ds.Tables[0]);

I have no idea, what the error means, by reading up the error its something to do with a null reference. Could anyone be able to tell me what the error is and how to fix it.

This is my class file (http://pastebin.com/38zW6Zk7):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EmployeeDatabse
{
  class DatabaseConnection
  {
    private string sql_string;
    private string strCon;
    System.Data.SqlClient.SqlDataAdapter da_1;

    public string sql
    {
      set { sql_string = value; }
    }

    public string connection_string
    {
      set { strCon = value; }
    }

    public System.Data.DataSet GetConnection
    {
      get { return MyDataSet(); }
    }

    public void UpdateDatabase(System.Data.DataSet ds)
    {

      System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
      cb.DataAdapter.Update(ds.Tables[0]);
    }

    private System.Data.DataSet MyDataSet()
    {
      System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
      con.Open();

      System.Data.SqlClient.SqlDataAdapter da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
      System.Data.DataSet dat_set = new System.Data.DataSet();
      da_1.Fill(dat_set, "Table_data_1");
      con.Close();

      return dat_set;

    }

  }

}
Nicholas Carey
  • 60,260
  • 12
  • 84
  • 126
  • 2
    are you initiating `cb` or `ds` anywhere in the code? Please post more code so we can help you – Wusiji Dec 18 '13 at 23:51
  • 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-and-how-do-i-fix-it) for some hints. – crthompson Dec 18 '13 at 23:55
  • I just read over the tutorial and didn't see any point where they are 'newing' up `cb`. – Brian Dec 18 '13 at 23:57
  • please if you can provide the whole code as you have written. – terrybozzio Dec 18 '13 at 23:59
  • According to the tutorial , which in my opinion is crap by the way, you should have System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder( da_1 ); some where in scope – Tony Hopkinson Dec 19 '13 at 00:04
  • u are probably calling the update before the method where you return the dataset,which is where you initialize the dataadapter. – terrybozzio Dec 19 '13 at 00:19
  • by the "wonderfull" tutorial it never calls GetConnection where the dataadapter is initialized.One way is in your Form load event set your dataset = ObjConnect.GetConnection; and it should go smooth.Remenber your objConect must set the 2 strings(the query and connectionstring)before this call to properly work. – terrybozzio Dec 19 '13 at 00:36

4 Answers4

1

That is a common exception in C# and it occurs when you use the dot operator on a null reference. What that means for you is that either cb or ds has a value of null when that line of code executes.

I looked at the tutorial you posted briefly but will not really be able to help based off of that because it doesn't have the code itself and I don't have the time to piece together all of the snippets and say "oh you never initialized ds" however, if you post an updated version of your code (more context is required, I need to see where cb and ds are declared/any place you set those values) I can give you a more specific solution.

There are a couple of approaches to fixing this; the first is to prevent null values altogether, and the second is to add nullity checks which prevent the raising of exceptions. I would personally recommend having both of these checks in place. Firstly, trace the value of those variables through app and make sure all code paths which lead to that line result in them being set, secondly you should probably have some of your logic enclosed within if statements of the form if (thisReference != null) { thisReference.DoSomething }

evanmcdonnal
  • 38,588
  • 13
  • 84
  • 107
  • Thanks for your reply, i have uploaded my code of my class file, that is where the problem is. if you need the form code let me know –  Dec 19 '13 at 00:08
  • @user3117267 so in your class the exception is thrown in `UpdateDatabase` if I understand correctly. `cb` is definitely not null (you're allocating the line before you use it). `ds` on the other hand is passed into that method, it could be any value. Check to make sure the `DataSet` you're passing it is not null. If it is you should use `GetConnection` to get a non-null `DataSet` and pass that to `UpdateDataBase`. – evanmcdonnal Dec 19 '13 at 00:31
  • @user3117267 Also worth noting, `MyDataSet()` does not use `using` statements or explicitly call `Dispose` on objects which implement `IDisoposable`. Any place you use a class that implements `IDisposable` you should declare the instance within a using statement like `using (SqlConnection con = new SqlConnection(strCon)) { //code that uses con }`. – evanmcdonnal Dec 19 '13 at 00:32
  • I have gone through it, but i have been following a tutorial, so tbh i have no idea what i am really looking for. All i know that its something with: cb.DataAdapter.Update(ds.Tables[0]); But i am not sure. Still very new to this all –  Dec 19 '13 at 08:34
  • @user3117267 well I just told you, `ds` is null. Check the call sites for `UpdateDatabase` you pass that method `ds` and one or more call sites is passing it a null reference. If you right click on the method somewhere in the editor you can select "Find All References" and it will provide you with a list of all the places that method is called. From there you can just set breakpoints before all of them, run the code, at every breakpoint confirm whether or not the argument you pass is null. In the place(s) it is do what's necessary to correct that. – evanmcdonnal Dec 19 '13 at 17:40
  • Ok so i have had a bit more indepth look. The tutorial only uses 4 data sets. I added more in to see if i can expand the code. It seems the code code i added was causing an issue. So when i run the program i can add and modify them. But when i close the program and re run it, there is no change to the databae is that normal? –  Dec 19 '13 at 22:25
  • @user3117267 no, it should be writing but I'm not very familiar with the `DataSet` class so I can't say off the top of my head whether or not you're using it correctly. I would check out examples on msdn, you might be missing a call to commit the changes or something to that effect. – evanmcdonnal Dec 19 '13 at 22:27
  • ok awesome, so i can get the most out of this, is there an alternative way to creating a database in SQL. I have had a look a youtube, but i seem to have an issue committing the Db to the project? –  Dec 19 '13 at 22:39
  • Sorted it, I had two lines of code that were confused. da_1 was not initialized and was Null. So it wouldn't work and update, now its working perfect. –  Dec 19 '13 at 22:52
  • Thanks for all your help –  Dec 19 '13 at 22:52
0

Check if you have tables inside your dataset(ds). If the dataset is not having any tables you may get that error.

Yousuf
  • 2,485
  • 2
  • 25
  • 36
0

A NullReferenceException (what you're getting) means you've tried to do something with a reference type that is null. In your failing line of code,

cb.DataAdapter.Update(ds.Tables[0]);

Any of these might be null:

  • cb
  • Its DataAdapter property (cb.DataAdapter)
  • ds
  • ds.Tables[0] (There's nothing that says a DataSet has to contain any tables. Or event o contain a table collection. Don't ask how I know this :D).

Without seeing context (how you're using your class) it's hard (impossible?) for us to say what the problem is.

However, you can easily sort out the problem in the debugger. Just put a breakpoint on the failing line and inspect the value of things when you hit the breakpoint.

Or, you can use assertions to assert your expectations. Injecting these statements, just prior to where the exception is thrown will identify the problem for you:

Debug.Assert( cb             != null , "cb is null" ) ;
Debug.Assert( cb.DataAdapter != null , "cb.DataAdapter is null" ) ;
Debug.Assert( ds             != null , "ds is null" ) ;
Debug.Assert( ds.Tables      !+ null , "ds.Tables is null" ) ;
Debug.Assert( ds.Tables.Count > 0    , "ds.Tables contains no tables" ) ;
Nicholas Carey
  • 60,260
  • 12
  • 84
  • 126
0

Object reference not set to an instance of an object

This usually happens when you try to call a method of a variable that is actually null. Always check your variables for null before attempting to call some method.

Note that you have a field called da_1 that is never initialized. Your MyDataSet method is creating a local variable called da_1 and not using the class variable. Then on your UpdateDatabase you try to create a SqlCommandBuilder passing da_1 which was not initialized. This might be the issue.

BrunoLM
  • 88,362
  • 76
  • 272
  • 427
  • I have gone through it, but i have been following a tutorial, so tbh i have no idea what i am really looking for. All i know that its something with: cb.DataAdapter.Update(ds.Tables[0]); But i am not sure. Still very new to this –  Dec 19 '13 at 08:27