Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay i dont seem to understand why i keep getting this error
Object refrence not set to an instant of an object

and im Getting it on connection.Open();
but i dont seem to understand why


here is the code im using

C#
public MySqlConnection connection;
       public void DBConnect()
       {
           Initialize();
       }
       private void Initialize()
       {
           string datasource = "";
           string initialcatalog = "";
           string uid = "";
           string pwd = "";
           string connectionstring;
           connectionstring = "SERVER='" + datasource + "';DATABASE='" + initialcatalog + "';UID='" + uid + "';PASSWORD='" + pwd + "'";
           connection = new MySqlConnection(connectionstring);
       }
       private bool OpenConnection()
       {
           try
           {
               connection.Open();
               return true;
           }
           catch (Exception ex)
           {
               switch (ex.Number)
               {
                   case 0:
                       System.Windows.Forms.MessageBox.Show("Cannot Connect to server. Contact administrator");
                       break;
                   case 1045:
                       System.Windows.Forms.MessageBox.Show("Invalid Username/Password for mysql, Please try again");
                       break;
               }
               return false;
           }
       }
Posted
Updated 3-Nov-10 21:27pm
v4

It appears that connection is null.
 
Share this answer
 
It looks like Initialise is never being run - are you calling DBConnect or Initialize before calling OpenConnection? Try putting a breakpoint in that method to see if it's called when you run your program.

Of course, I can't see the rest of the class, but I assume that you mean for DBConnect to be the constructor. If that's the case, it shouldn't have the void keyword in front of it, and you also need to make sure it has the same name as the class in which it resides.
 
Share this answer
 
Try to change this part of the code to this one:

connectionstring = "SERVER=" + datasource + ";DATABASE=" + initialcatalog + ";UID=" + uid + ";PWD=" + pwd;
 
Share this answer
 
v2
you r getting the error means your connection is emptyie null

if it is ur local system u just require 3 things only one is database name and userid and password

ex-database="dbname";userid="sa";pwd="sa";
try this one also
 
Share this answer
 
I cannot see where you are calling OpenConnection() from. Are you sure you are not calling this method before your Initialize() method, and so the connection object is not being initialized ?
 
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