Object reference not set to an instance of an object. - App.config
Asked Answered
R

7

6

I receiving the error and in the local window I am seeing for both conSettings and connectionString value of null. I am right to say ConfigurationManager is null and I need to create a new object. Maybe I am using Access and perhaps I have missed something in App.config file. Can someone help me on how to solve this problem, please. Thanks in advance.

App.config file...

   <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <appSettings>
       <add key="MyDBConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data 
                   Source=E:\...\Database1.mdb"/>
    </appSettings>
    </configuration>

Form.cs file...

 private void btnShow_Click(object sender, EventArgs e)
    {
        ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];

        string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here

        try
        {
            con = new OleDbConnection(connectionString);
            con.Open();
            cmd = new OleDbCommand("SELECT * FROM Table1", con);
            objReader = cmd.ExecuteReader();
            while (objReader.Read())
            {
                txtID.Text = ds.Tables[0].Rows[rno][0].ToString();
                CBAgeGroup.Text = ds.Tables[0].Rows[rno][1].ToString();
                CBGender.Text = ds.Tables[0].Rows[rno][2].ToString();
                CBCrimOffen.Text = ds.Tables[0].Rows[rno][3].ToString();
                if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value)
                {
                    photo_aray = (byte[])ds.Tables[0].Rows[rno][4];
                    MemoryStream ms = new MemoryStream(photo_aray);
                   pictureBox1.Image = Image.FromStream(ms);
                }
                txtCV.Text = ds.Tables[0].Rows[rno][5].ToString();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

I have been advised to use App.config.

VS 2010 C# MS Access 2003

UPDATE 1 My App.config now looks like this...

<configuration>
    <ConnectionString>
        <add key="MyDBConnectionString"   value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Raj\Education\C_Sharp\Test1\Database1.mdb"/>
    </ConnectionString>

I am now receiving error of..."Configuration system failed to initialize". I am looking at it now on Google.

Update 2 Tried...

<configuration>
 <connectionStrings>
<add name="MyDBConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data   
        Source=E:\...\Database1.mdb"/>
  </connectionStrings>
 </configuration>

Receiving error of "Object reference not set to an instance of an object" Googling again

Update 3

<configuration>
<connectionStrings>
    <clear />
    <add name="MyDBConnectionString"
     providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Source=\Database1.mdb" />
</connectionStrings>

With the update 3 I am receiving error the same error. I have included the Add reference System. Configuration and I have referenced using System.Configuration;

Conclusion

Perhaps it maybe there is a technical gitch between VS 2010 and Access 2003. I shall not use App.config this time round. I know there will be no problem with SQL Server. So I will leave it that. Thanks Damith and Clint for your time.

Rosewater answered 21/4, 2013 at 13:0 Comment(0)
E
10

you need to read AppSettings key as below ,

string connectionString = 
      ConfigurationSettings.AppSettings["MyDBConnectionString"];

still you receive empty value, try below steps

  1. Select the App.Config file in the solution explorer
  2. In the property window select Copy to Output Directory to Copy Always.
  3. Now Build the application and try again.

to access like below you need to add connectionStrings section in app config

  string connectionString = 
      ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here

sample app config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyDBConnectionString" 
    connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data 
               Source=E:\...\Database1.mdb"/>
  </connectionStrings>
</configuration>
Emprise answered 21/4, 2013 at 13:6 Comment(4)
That would work, but Microsoft have the connection strings section of the app.config for a reason and their official guidelines say that section ought to be used for connection strings.Redfin
@Emprise - I have tried conntectionString and I am receiving error message of "Object reference not set to an instance of an object". Please can you advise me?Rosewater
@Rosewater are you sure, you set app config copy to out put directory always ?Emprise
@Emprise - Yes I made sure of that. I am using MSDN guidelines given my ClintRosewater
V
10

Check if you have put the app.config file under your startup project or not. In my case, I just had to put the app.config file under my startup project, and problem was solved.

Vilhelmina answered 26/5, 2013 at 16:43 Comment(0)
S
3

This happened to me in class library with a console app set to run for debugging.

It is necessary to add the connection to the app.config in the console app, as it will not find it in your library if you're starting it from an outside process.

Streit answered 22/3, 2017 at 20:18 Comment(1)
Whoops! In my case, I was trying to use web.config instead of app.config in my web form stub.Amaral
R
1

This:

string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

is your problem.

You're accessing ConfigurationManager.ConnectionStrings to get to your configuration item, but in the App.Config file you've put it under appSettings which is a different section of the config file than ConnectionStrings

You could either put your connection string in the relevant ConnectionStrings section of the app.config (accessible with ConfigurationManager.ConnectionStrings, or access it against the appSettings section.

See:

http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx

For MSDN guidelines on storing connection strings.

Redfin answered 21/4, 2013 at 13:9 Comment(2)
I have done what you have advised and I am getting error of Configuration system failed to initialize. I am looking searching on the Goggle to find out what it isRosewater
@Rosewater follow the example in the MSDN guidelines exactly, it could be you've not got the details in the connectionstring section of the file quite right.Redfin
H
1

I too faced the same problem even after multiple scrutinizing the app.config files and my code for error, but i didn't found any errors in my code. Eventually i found a silly mistake that my compiler had by default taken the application configuration file name as 'app1.config', and when i changed it to 'app.config' every thing just worked fine for me.

Hope it will help.

Hylotheism answered 2/5, 2016 at 6:6 Comment(0)
N
0

I bumped into this problem when I added app.config file by Project -> Add -> New Item... -> Application Configuration File to an old, tiny C# library that had been originaly written in .NET Framework 4.5 and later updated to 4.7.2. After many attempts I decided to load config file just as a XML file. If everything else failed you may consider using this workaround.

App.settings

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="MyDBConnectionString"
         providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Source=\Database1.mdb" />
    </connectionStrings>
</configuration>

Code behind

using System;
using System.IO;
using System.Reflection;
using System.Xml;

XmlDocument doc = new XmlDocument();
string path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) + "\\YourProjectName.exe.config";
doc.Load(path);

XmlNode node = doc.SelectSingleNode("//connectionStrings");
XmlElement value = (XmlElement)node.SelectSingleNode("//add[@name='MyDBConnectionString']");

string connectionString = value.Attributes["connectionString"].Value;

The effect should be similar to:

string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ToString();
OR
string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

Hope that someone will find this useful.

Nonanonage answered 22/2, 2023 at 13:46 Comment(0)
V
0

1-go to solution explorer 2-click on App.config 3-change the connection name or add new like this in the above code pre_test is the name of the project and if you changed your project name you have to chnage this name

Villous answered 15/8, 2023 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.