locked
Getting ConnectionString from app.config RRS feed

  • Question

  • Hello everyone, I can't get my connection to work properly.

    This is my app.config

    <?xml version="1.0" encoding="utf-8" ?><configuration>  <connectionStrings>    <add name="BO"        connectionString="Data Source=TPHP3175;Initial Catalog=BO;User ID=User;Password=passwd"        providerName="System.Data.SqlClient" />  </connectionStrings></configuration>


    And in my class.cs

    using (SqlConnection conn = getNewConnection("BO")) {...code}
    public static SqlConnection getNewConnection(string x)
            {
                string connection = ConfigurationManager.ConnectionStrings["BO"].ConnectionString.ToString();
                var conn = new SqlConnection(connection);
                return conn;
            }

    (the 'x' parameter will be used later on the process, no need to worry about it)

    I get the error "Object reference not set to an instance of an object" in the line 

    string connection = ConfigurationManager.ConnectionStrings["BO"].ConnectionString.ToString();

    It's like I have to "new" the object but all I want to do is getting the sqlconnection from the app.config.

    Thanks for any kind of help.



    • Edited by DSlinx Thursday, June 21, 2012 11:13 AM
    Thursday, June 21, 2012 10:55 AM

Answers

  • Please execute the following code inside your application. It will show you all names of your ConnectionStringSettings inside the ConnectionStringSettingsCollection:

                ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
                foreach (ConnectionStringSettings setting in connections)
                {            
                    MessageBox.Show(setting.Name);
                }

    I didn`t set any Connectionstring inside my app.config and also got 3 ( by default ) connectionstringsettings:

    LocalSqlServer
    LocalVistaDBDatabase
    LocalMySqlServer


    Hannes

    If you have got questions about this, just ask.

    In a perfect world,
    users would never enter data in the wrong form,
    files they choose to open would always exist
    and code would never have bugs.

    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/

    • Marked as answer by Bob Shen Tuesday, July 3, 2012 9:51 AM
    Friday, June 22, 2012 6:26 AM

All replies

  • Could you please check BonnieB's answer in below thread

    http://social.msdn.microsoft.com/Forums/en/winforms/thread/62e5c178-16a9-46a0-a153-7b3b58ad71e7


    Regards,
    Ahmed Ibrahim
    SQL Server Setup Team
    My Blog
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click "Mark as Answer" and "Vote as Helpful" on posts that help you.
    This can be beneficial to other community members reading the thread.

    Thursday, June 21, 2012 10:57 AM
  • Thanks for the reply Ahmed.

    I've came across with the thread you recommended me.

    And that could actually work but if you see my code, In the: using (SqlConnection conn = getNewConnection("BO"))

    I need a SqlConnection, not a string. So, in order to follow Bonnie's advice I'd need to know how to get a SqlConnection from

    string MyConnectionString = connections["MyConnection"].ConnectionString;

    Or changing my "using" statement to receive and connect to the server from a string instead of a SqlConnection.

    Thanks.



    Thursday, June 21, 2012 11:07 AM
  • Hi,

    You can do like this:

    using (SqlConnection conn = new SqlConnection(connections["MyConnection"].ConnectionString))
    {
        //code
    }

    Or if you need the GetNewConnection() function:

    using (SqlConnection conn = GetNewConnection()) { //code }

    public static SqlConnection getNewConnection(string x) { string connection = connections["MyConnection"].ConnectionString; var conn = new SqlConnection(connection); return conn; }


    • Edited by MukiJames Thursday, June 21, 2012 11:22 AM
    Thursday, June 21, 2012 11:16 AM
  • Hi,

    You can do like this:

    using (SqlConnection conn = new SqlConnection(connections["MyConnection"].ConnectionString))
    {
        //code
    }

    Or if you need the GetNewConnection() function:

    using (SqlConnection conn = GetNewConnection(connections["MyConnection"].ConnectionString))
    {
        //code
    }

    I take your second option since I need to use the method getnewconnection, but when I follow your advice I get the "connections does not exist in the current context" which is logic since I havent declared it outside of GetNewConnection. Any advice?
    Thursday, June 21, 2012 11:21 AM
  • Thursday, June 21, 2012 11:22 AM
  • Did you check that app.config placed correctly with correct name beside the exe ?

    Regards,
    Ahmed Ibrahim
    SQL Server Setup Team
    My Blog
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click "Mark as Answer" and "Vote as Helpful" on posts that help you.
    This can be beneficial to other community members reading the thread.

    Thursday, June 21, 2012 11:23 AM
  • Hi,

    True, I made a mistake. The code should look like this:

    using (SqlConnection conn = GetNewConnection())
    {
        //code 
    }
    
    public static SqlConnection getNewConnection(string x) 
    { 
        string connection = ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
        var conn = new SqlConnection(connection); 
        return conn; 
    }
    

    Thursday, June 21, 2012 11:30 AM
  • Following your advices I've made these changes.

     public static string getNewConnection(string x)
            {
                ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
                string MyConnectionString = connections["BO"].ConnectionString;
                return MyConnectionString;

            }

     string connectionString = getNewConnection("BO");
     using (SqlConnection conn = new SqlConnection(connectionString))

    But still it errors "Object reference not set to an instance of an object" in the line 

    string MyConnectionString = connections["BO"].ConnectionString;

    Ahmed: I can't tell of any error withing the app.config file.

    Thursday, June 21, 2012 11:34 AM
  • the app.config should be copied and be in the same folder as your exe

    so if you exe is called foo.exe

    you should have the app.config copied as foo.exe.config.


    Regards,
    Ahmed Ibrahim
    SQL Server Setup Team
    My Blog
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click "Mark as Answer" and "Vote as Helpful" on posts that help you.
    This can be beneficial to other community members reading the thread.

    Thursday, June 21, 2012 11:38 AM
  • For me it looks like you don't have a connection string named "BO" in your app.config.Debug to your code and check the content of your ConnectionManager.ConnectionStrings. Does it even contain anything? (Count not 0)...

    • Marked as answer by DSlinx Thursday, June 21, 2012 12:31 PM
    • Unmarked as answer by DSlinx Thursday, June 21, 2012 12:31 PM
    Thursday, June 21, 2012 11:42 AM
  • Oh I see.

    I have no .exe (I mean, im just debugging). I'm just working in the class.cs (later on it will be accessed from php files), and for testing purposes I created a Windows Form with a simple button to display in a DataGrid a simple Select * from table from the desired connection.


    The app.config was created in the same project as class.cs. Does this answer your question? Thanks a lot again.


    • Edited by DSlinx Thursday, June 21, 2012 11:46 AM explanation
    Thursday, June 21, 2012 11:42 AM
  • For me it looks like you don't have a connection string named "BO" in your app.config.Debug to your code and check the content of your ConnectionManager.ConnectionStrings. Does it even contain anything? (Count not 0)...

    I did it, count = 3!
    Thursday, June 21, 2012 12:32 PM
  • The out put of compilation should be either dll or exe correct ?

    Regards,
    Ahmed Ibrahim
    SQL Server Setup Team
    My Blog
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click "Mark as Answer" and "Vote as Helpful" on posts that help you.
    This can be beneficial to other community members reading the thread.

    Friday, June 22, 2012 3:32 AM
  • Please execute the following code inside your application. It will show you all names of your ConnectionStringSettings inside the ConnectionStringSettingsCollection:

                ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
                foreach (ConnectionStringSettings setting in connections)
                {            
                    MessageBox.Show(setting.Name);
                }

    I didn`t set any Connectionstring inside my app.config and also got 3 ( by default ) connectionstringsettings:

    LocalSqlServer
    LocalVistaDBDatabase
    LocalMySqlServer


    Hannes

    If you have got questions about this, just ask.

    In a perfect world,
    users would never enter data in the wrong form,
    files they choose to open would always exist
    and code would never have bugs.

    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/

    • Marked as answer by Bob Shen Tuesday, July 3, 2012 9:51 AM
    Friday, June 22, 2012 6:26 AM