Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to C#. I'm having problem in this part of coding. Sometime it runs well. When i debug again it said the object reference not set to an instance of an object. When I do break point. I find it the part of 'for' looping is the cause of problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace DynamicSimulator
{
    class saveDatabase
    {
        #region Object Declaration
        protected MySqlConnection conn;
        protected MySqlCommand command;
        protected frmCreateDB dbase = new frmCreateDB();
        #endregion

        #region Local Variables
        protected int i;
        protected string connStr = string.Empty;
        protected string database = string.Empty;
        #endregion

        #region Constructor
        public saveDatabase(frmMain Main)
        {
            database = dbase.getModelName;
            connStr = "datasource=localhost;port=3306;username=root;password=root;";

            conn = new MySqlConnection(connStr);

            command = conn.CreateCommand();
        }
        #endregion
    }

    class saveMetabolites : saveDatabase
    {
        public saveMetabolites(frmMain Main)
            : base(Main)
        {
            //Insert Metabolites Values
            conn.Open();
            //Start this part, the code stop debug and said the object reference not set to an instance of an object
            for (i = 0; i < Main.dbMetName.Rows.Count; i++)
            {

                command.CommandText = "INSERT INTO " + database +
                                      ".Metabolites " +
                                      "(MetaboliteID, Metabolite_Name)" +
                                      "VALUES " +
                                      "('" + Main.dbMetName.Rows[i].Cells[0].Value.ToString() +
                                      "' , '" + Main.dbMetName.Rows[i].Cells[1].Value.ToString() + "')";
                command.ExecuteNonQuery();
            }
            conn.Close();

            //Insert Dynamic Equations Value
            conn.Open();
            for (i = 0; i < Main.dbDynamicEq.Rows.Count; i++)
            {
                command.CommandText = "UPDATE " + database +
                                      ".Metabolites " +
                                      "SET DynamicEq = " +
                                      "'" + Main.dbDynamicEq.Rows[i].Cells[1].Value.ToString() + "'" +
                                      "WHERE Metabolite_Name = " +
                                      "'" + Main.dbMetName.Rows[i].Cells[1].Value.ToString() + "'";
                command.ExecuteNonQuery();

                command.CommandText = "UPDATE " + database +
                                      ".Metabolites " +
                                      "SET Initial_Condition = " +
                                      "'" + Main.dbDynamicEq.Rows[i].Cells[2].Value.ToString() + "'" +
                                      "WHERE Metabolite_Name = " +
                                      "'" + Main.dbMetName.Rows[i].Cells[1].Value.ToString() + "'";
                command.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

    class saveCoMetabolites : saveDatabase
    {
        public saveCoMetabolites(frmMain Main)
            : base(Main)
        {
            //Insert Co-Metabolites Values
            conn.Open();
            for (i = 0; i < Main.dbCoMetName.Rows.Count; i++)
            {
                command.CommandText = "INSERT INTO " + database +
                                      ".CoMetabolites " +
                                      "(CoMetaboliteID, CoMetabolite_Name)" +
                                      "VALUES " +
                                      "('" + Main.dbCoMetName.Rows[i].Cells[0].Value.ToString() +

                                      "' , '" + Main.dbCoMetName.Rows[i].Cells[1].Value.ToString() + "')";
                command.ExecuteNonQuery();
            }
            conn.Close();
        }
    }
Posted
Updated 27-May-14 22:19pm
v2
Comments
Sergey Alexandrovich Kryukov 28-May-14 1:13am    
If "for loop"? Which one? Please mark the line throwing the exception by a comment...
—SA
arave0521 28-May-14 4:20am    
I had insert the comment
Sergey Alexandrovich Kryukov 28-May-14 11:36am    
It's not precise enough. If you mean the for loop itself (not its body), it is 3 statements, and the exception could be thrown in only in the expression Main.dbMetName.Rows.Count. But from your comment, I cannot be 100% certain.
—SA
syed shanu 28-May-14 2:10am    
I think in this method
public saveMetabolites(frmMain Main)
: base(Main)
{
conn.Close();

//Insert Dynamic Equations Value
conn.Open();

}

You have used con.close() and then con.Open().
check with your break point where you get error.
arave0521 28-May-14 4:21am    
the problem started when it want to enter the for loop of metabolite class. I had insert the comment of the problem arise

Not sure, just try this:

Define and initialize your command where you are using.
In the loop that throws the exception, have two commands instead of one.
 
Share this answer
 
v2
Please see my most recent comment: you did not pinpoint the piece of code throwing the exception precisely. From your comment, one could assume it was thrown in Main.dbMetName.Rows.Count, so Main could be null, if not, Main.dbMetName could be null. This is what the debugger is for, to study such situations.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900