Click here to Skip to main content
13,899,460 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
hi , i have a datagrid connected to a database, alongside it is 2 buttons, 1 -update 2 - refresh ,
button one updates the datagrid with the newly entered entries while the refresh just refreshes ,
heres the code
 public partial class Form1 : Form
    {
        SqlDataAdapter sda;
        SqlCommandBuilder scb;
        DataTable dt;

        public Form1()
        {
           
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'testDataSet.loanf' table. You can move, or remove it, as needed.
            this.loanfTableAdapter.Fill(this.testDataSet.loanf);
          

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
            sda = new SqlDataAdapter(@"SELECT NAME, AMOUNT, DATE
                                    FROM        loanf",con);
            dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.DataSource = dt;


        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            scb = new SqlCommandBuilder(sda);
            sda.Update(dt); 
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

but whenever i click on the update button , to save the entries i get the error _>
Object reference not set to an instance of an object .  thanks in advance :)

What I have tried:

google,,youtube
changing tables
recreating whole program
recreating tables
changing keys
Posted
Updated 29-Jun-16 4:04am
Comments
ZurdoDev 29-Jun-16 9:56am
   
This is a very easy thing for you to fix. Something is null, and you need to fix that.
jamesmc1535 29-Jun-16 10:17am
   
but where? XD , starting it over again as i dont see the null value,
ZurdoDev 29-Jun-16 10:24am
   
Where? We can't possibly know. But when you run it the code will stop somewhere and give you that error. That's what you need to look at.
jamesmc1535 29-Jun-16 10:29am
   
sda.Update(dt);
ZurdoDev 29-Jun-16 10:37am
   
So, what on that line is null? Likely dt. But you have to debug it.
Member 12599256 29-Jun-16 10:00am
   
Use debugger, debug it line by line, then you can see which line throw an exception.
jamesmc1535 29-Jun-16 10:23am
   
thanks ill try that quickly
jamesmc1535 29-Jun-16 10:25am
   
sda.Update(dt); <
Sergey Alexandrovich Kryukov 29-Jun-16 10:03am
   
In what line?
—SA
jamesmc1535 29-Jun-16 10:25am
   
sda.Update(dt);
Sergey Alexandrovich Kryukov 29-Jun-16 11:03am
   
Check up if sda is null at the moment of the call... Follow the steps I described in my answer...
—SA
jamesmc1535 29-Jun-16 11:07am
   
thanks, i sortoff fixed it, the datagrid updates into the database now , without problems, but i cant delete a row in the datagrid ( as i have no collum as primary key , but when i set a collum to primary i get that null error
Sergey Alexandrovich Kryukov 29-Jun-16 11:11am
   
Why no primary key? Anyway, nothing prevents you from deleting a row. To fix another null exception, follow the steps I described again... :-)
—SA
jamesmc1535 1-Jul-16 3:38am
   
thanks for the help , :)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
   
Comments
jamesmc1535 29-Jun-16 10:16am
   
very nice explanation , i have no idea where i went wrong , doing it over again :) thanks alot
OriginalGriff 29-Jun-16 10:29am
   
You're welcome!
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferences 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
   

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


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190306.1 | Last Updated 29 Jun 2016
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100