Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It may look a duplicate but I've used the search engine for days just to clear out this error "object reference not set to an instance of an object".
When I run the code in debug mode, it executes but on deploying and installing it on the same machine, an error generates.

What I have tried:

// App.config
<connectionStrings>
    <add name=" SSM.Properties.Settings.ScMgP"
      connectionString="server=localhost;user id=root;password=xxxx;database=ssmp;persistsecurityinfo=True;port=3306"
      providerName="MySql.Data.MySqlClient" />
  </connectionStrings>


//form.cs
using System;
using MySql.Data.MySqlClient;
using System.Configuration;

      private void txtP_TextChanged(object sender, EventArgs e)
        {
            connUN.ConnectionString = ConfigurationManager.ConnectionStrings["SSM.Properties.Settings.ScMgP"].ConnectionString;
       try
           {
               MySqlCommand cmd = new MySqlCommand();
               MySqlDataReader ReaderUN;
               connUN.Open();
               cmd.Connection = connUN;
               cmd.CommandText = "Select * from system where password ='" + txtP.Text + "'  ";
               ReaderUN = cmd.ExecuteReader();
               if (ReaderUN.Read())
               {
Department Form = new Department();Form.Show();this.Hide();
}
               connUN.Close();
           }
           catch (Exception ex)
           {
MessageBox.Show("Failed to connect to database... system error Message.   " + ex.Message, "Database connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
            finally{}
        }
Posted
Updated 7-Mar-19 7:26am
Comments
MadMyche 7-Mar-19 12:43pm    
Is the exception just occurring or does you message box open?
Robert S4r 7-Mar-19 12:46pm    
Message box opens

That message merely indicates that you are trying to use an object reference that has not been initialised. The first thing you need to do is find the line of code where it occurs and diagnose why the reference is null.

And, as a side note, do not use string concatenation ("Select * from system where password ='" + txtP.Text + "' ") in SQL. Use proper parameterised queries. And never store passwords in clear text, it leaves your entire system open to hackers. Use salted and hashed values.
 
Share this answer
 
v2
Comments
Robert S4r 7-Mar-19 12:03pm    
It indicates at line

connUN.ConnectionString = ConfigurationManager.ConnectionStrings["SSM.Properties.Settings.ScMgP"].ConnectionString;
You don't read anything from the app.config file. When you use the config manager it looks for a config name that matches the executable, so if your program is "MyApp.exe" then your config file needs to be called "MyApp.exe.config". App.config is just a placeholder name, when you publish your code VisualStudio copies the app.config contents to a file with the correct name.
 
Share this answer
 
v2
Comments
Robert S4r 7-Mar-19 12:53pm    
I've renamed the app.config to SSM.config. "(from SSM.exe)".
now the NullReferenceException occurs on debug at line
var connection = ConfigurationManager.ConnectionStrings[ScMgP].ConnectionString;

Line modified
F-ES Sitecore 7-Mar-19 13:02pm    
It has to be SSM.exe.config
Robert S4r 7-Mar-19 14:30pm    
Solved successfully! Thanks a lot.
A couple of things I noticed:

Where is connUN defined?
C#
private void txtP_TextChanged(object sender, EventArgs e)
  {
    connUN.ConnectionString = ConfigurationManager.ConnectionStrings["SSM.Properties.Settings.ScMgP"].ConnectionString;
Why have you done it this way? Have you thought about trying something like this?
C#
private void txtP_TextChanged(object sender, EventArgs e)
  {
    string _cs = ConfigurationManager.ConnectionStrings["SSM.Properties.Settings.ScMgP"].ConnectionString;
    using (SqlConnection connUN = new SqlConnection(_cs)) {


Next thing is the way you build this command up. It is downright dangerous! NEVER EVER should you piece together an SQL Command from inline strings containing user input. This is a prime example of SQL Injection, and has been in the top 10 vulnerabilities for over 20 years. The proper way would be to used Parameters and adding the user input by adding the values later. Here is the relevant block of code building on my previous code sample
C#
try {
  SqlCommand cmd = new SqlCommand(_qry, connUN);
  cmd.Parameters.AddWithValue("@password", txtP.Text());


And the last thing is your error handling. It assumes every every thrown is with the database. There are options, and you can stack the catch statements to display better information about your mistake. The only rule is that the generic catch (Exception ex) is last, as it will catch any exception. By using a specific MySqlException catch you can access the properties specific to MySql.
SQL
catch (MySqlException sx) {
  MessageBox.Show(
    "MySql Exception " + sx.Message
    , "Database error #" + sx.Code
    , MessageBoxButtons.OK
    , MessageBoxIcon.Error
  );
}
catch (Exception ex) {
  MessageBox.Show(
    "System error Message.   " + ex.Message
    , "General Error"
    , MessageBoxButtons.OK
    , MessageBoxIcon.Error
  );
}


I cannot guarantee that this will fix your requested problem, but these blocks of code are safer and can be more informative when you do have a problem.
 
Share this answer
 
Comments
Robert S4r 7-Mar-19 14:48pm    
Thanks for that extra advise! Appreciated!

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