Jahan Ahmed Abbasi Jahan Ahmed Abbasi - 1 month ago 7
ASP.NET (C#) Question

Connection string property of SqlConnection is not initialized

I have already searched for the error


the connection string property has not been initialized.


on Google as well as on Stack Overflow but couldn't find the solution. I have created a database class for interaction with database all related code is written in this file. The problem is same code runs fine on other pages and it just don't work on a page called "addevent.aspx" I don't understand the reason why it is not running properly.

Here are the methods that I created in database.cs file

public void CreateConnection()
{
var ConfiguredString = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
obj_sqlconnection = new SqlConnection(ConfiguredString);

}

//This property will set the connection string for database
public string ConnectionString
{
get
{ //if _connectionString is already created or set, only then it will return the value of _connectionString
if (_connectionString != string.Empty && _connectionString != "" && _connectionString != null)
return _connectionString;
else
return string.Empty;
}
// When you want to set the connection string set block is called.
set
{ // this line sets the connection string to the _connectionString data member for the first time.
if (_connectionString == string.Empty || _connectionString == "" || _connectionString == null)
_connectionString = value;
}
}

// Open database connection.
public void OpenConnection()
{
obj_sqlconnection.Open();
}

// Close database connection.
public void CloseConnection()
{
obj_sqlconnection.Close();
obj_sqlconnection.Dispose();
}

public SqlConnection GetCurrentConnection
{
get { return obj_sqlconnection; }
set { obj_sqlconnection = value; }
}


I simply don't understand the logic of this error and its occurrence. I get this error when I open the connection

How do I call these methods, I have already created a object of database.cs class outside the method AddEvent with object name mydb

public int AddEvent(string _title, string _description, string _place, int _eventTypeID, string _startingTime, string _endingTime, string _startingDate, string _endingDate, string _creatorID, string _picture)
{
string[] blacklist = { _title, _description, _place, _picture };

if (Jvalidate.FilterBlackLIstKeywords(blacklist))
{
int eventid = Convert.ToInt32(mydb.GetLastValueByColumnName("event_id", "tbl_events"));
int rowsaffected = 0;
mydb.CreateConnection();

mydb.InitializeSQLCommandObject(mydb.GetCurrentConnection, "spAddEvent", true);
mydb.obj_sqlcommand.Parameters.AddWithValue("@eventID", eventid + 1);
mydb.obj_sqlcommand.Parameters.AddWithValue("@title", _title);
mydb.obj_sqlcommand.Parameters.AddWithValue("@description", _description);
mydb.obj_sqlcommand.Parameters.AddWithValue("@place", _place);
mydb.obj_sqlcommand.Parameters.AddWithValue("@eventType", _eventTypeID);
mydb.obj_sqlcommand.Parameters.AddWithValue("@startingTime", _startingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("@endingTime", _endingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("@startDate", _startingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("@endDate", _endingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("@schoolID", SchoolID);
mydb.obj_sqlcommand.Parameters.AddWithValue("@eventCreatorID", _creatorID);
mydb.obj_sqlcommand.Parameters.AddWithValue("@eventPicture", _picture);
try
{
//mydb.obj_sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["cesConnectionString"].ToString();
mydb.OpenConnection();
rowsaffected = mydb.obj_sqlcommand.ExecuteNonQuery();
}
finally
{
mydb.CloseConnection();
mydb.obj_sqlcommand.Dispose();
}
return rowsaffected;
}
return 0;
}

Answer

it's too complicated solution... this will solve your problem of understanding and unnecessary code lines.

namespace Stackoverflow
{
    public class Solution
    {
        public static object SqlExecute(
            string connectionStringName,
            string storedProcedureName,
            System
                .Collections
                .Generic
                .Dictionary<string, object> parameters,
            bool isScalar)
        {
            object result = null;

            using (System.Data.SqlClient.SqlConnection connection =
                new System.Data.SqlClient.SqlConnection(
                        System.
                        Configuration.
                        ConfigurationManager.
                        ConnectionStrings[connectionStringName].
                        ConnectionString))
                if (connection != null)
                    using (System.Data.SqlClient.SqlCommand command =
                        new System.Data.SqlClient.SqlCommand()
                        {
                            CommandText = storedProcedureName,
                            CommandType = System
                                              .Data
                                              .CommandType
                                              .StoredProcedure,
                            Connection = connection
                        })
                        if (command != null)
                        {
                            if (parameters != null)
                                foreach (System
                                             .Collections
                                             .Generic
                                             .KeyValuePair<string, object>
                                                 pair in parameters)
                                    command.Parameters.AddWithValue(
                                        pair.Key, pair.Value);

                            command.Connection.Open();

                            result = isScalar
                                ? command.ExecuteScalar()
                                : command.ExecuteNonQuery();

                            if (command.Connection.State ==
                                    System.Data.ConnectionState.Open)
                                command.Connection.Close();
                        }

            return result;
        }

        public void Example()
        {
            Solution.SqlExecute(
                @"cesConnectionString",
                @"anyStoredProcedureName",
                new System.Collections.Generic.Dictionary<string, object>(){
                    { @"field1", 1 },
                    { @"field2", 1.5 },
                    { @"field3", "two" },
                    { @"field4", 3.5 },
                    { @"field5", "four" },
                },
                false
            );
        }
    }
}