Chris Hadfield
Chris Hadfield

Reputation: 524

C# - The ConnectionString property has not been initialized

I am just learning c#. I am trying to make simple CRUD in c# windows form but got some error there. The error says The ConnectionString property has not been initialized. Below code shows how i have tried.

App.config for connection with SQL SERVER

<connectionStrings>
<add name="connectionstr" connectionString="Data Source=DESKTOP-F8UCLUB;Initial Catalog=bug_tracker;Integrated Security=True" />

DBConnection class

class DBConnection
{
    private string connectionString = ConfigurationManager.ConnectionStrings["connectionstr"].ConnectionString;

    public SqlConnection GetConnection()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            return connection;
        }
    }
}

Function to insert

 public void Insert(Programmer t)
    {
        conn.Open();
        IDbTransaction trans = null;

        try
        {
            conn.BeginTransaction();

            SqlCommand sql = new SqlCommand(null, conn);
            sql.CommandText = "INSERT INTO tbl_programmer VALUES(@fullName, @username, @password)";
            sql.Parameters.AddWithValue("@fullName", t.FullName);
            sql.Parameters.AddWithValue("@username", t.Username);
            sql.Parameters.AddWithValue("@password", t.Password);

            sql.Prepare();
            sql.ExecuteNonQuery();

            trans.Commit();
        }
        catch (SqlException ex)
        {
            trans.Rollback();
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }

Upvotes: 2

Views: 10755

Answers (2)

user7148391
user7148391

Reputation:

The SqlConnection Object get disposed since you're using it inside the using which calls Dispose() on it.

And if you're going to return something, it must not be disposed, It has to stay in memory.

If you wanna have more understanding of how this works then i'll try my best :

The return statement returns back the address of the Object, then later dispose() get called on that object, by now that address doesn't hold that Object anymore, therefor that exception is thrown.

Upvotes: 2

The problem is using keyword. using directive only be use disposable objects.

If you create any instance in using block, the instance disposible out of curly braces..

 public SqlConnection GetConnection()
    {
        SqlConnection connection = new SqlConnection(connectionString);
            if (connection.State == ConnectionState.Closed)                
                connection.Open();

            return connection;            
    }

Upvotes: 9

Related Questions