Raika
Raika

Reputation: 37

The ConnectionString property has not been initialized. How to fix it?

I am using a method(GetConnectionString()) in a class(Utility.cs) as part of another method(fillDT()) in another class(Function.cs).

internal class Utility
{
    internal static string GetConnectionString()
    {
        //Util-2 Assume failure.
        string returnValue = null;

        //Util-3 Look for the name in the connectionStrings section.
        ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Assignment_new.Properties.Settings.connString"];

        //If found, return the connection string.
        if (settings != null)
            returnValue = settings.ConnectionString;

        return returnValue;
    }
}

class Functions
{
    public static DataTable fillDT(string sqlstatement) //Fills the datatable with data from sqlstatement
    {
        string connstr = Assignment_new.Utility.GetConnectionString();
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter(sqlstatement, con);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }

Whenever I call Functions.fillDT(@"sql statement"), the error pops out saying connection string is not initialized.

Upvotes: 1

Views: 527

Answers (2)

brainless coder
brainless coder

Reputation: 6430

Make sure you use proper config files to save your connection string. I see you are tagging this question as WinForms, so your connection string should be inside App.Config file not in Web.Config. If this a web application then you should do the opposite, keep it in Web.Config file at the top most directory.

Also, if this is a desktop application and you are using App.Config file to save your settings, make sure that file is copied to your output directory, where the executable stays (usually the same name as the executable. i.e <EXNAme>.exe.config). Otherwise when the application runs, it won't find it.

Upvotes: 1

Saeid
Saeid

Reputation: 1663

You just checked your connection string to be null. Check string.IsNullOrEmpty() to see if it's not null. Besides, you need to set breakpoint and check if the connection string value you see in your app.config actually retrieved in your code and it is correct.

Upvotes: 0

Related Questions