ananth reddy ananth reddy - 1 month ago 18
C# Question

ExecuteReader: Connection property has not been initialized

I understand that this question has been asked many times but the error with
connection is giving me a hard time.


ExecuteReader: Connection property has not been initialized


I'm trying to search for a phone number from a table. I have tried almost all the solutions given in other threads but couldn't seem to figure out how to rectify the error. I have to associate command with sqlconnection but i couldn't do that.

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

using( SqlCommand cmd1 = new SqlCommand() )
{
conn.Open();

cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "SearchName";
SqlParameter p1 = new SqlParameter();
p1.ParameterName = "@Name";//Stored Proc
p1.Value = SearchbyName.Name;
cmd1.Parameters.Add(p1);

using (SqlDataReader dr = cmd1.ExecuteReader())
{
if (dr.Read())
{
while (dr.Read())
{
Console.WriteLine(dr[0] + " " + dr[1]);
}
SearchExit();
}
else
{
Console.WriteLine("No contact found with name {0}", SearchbyName.Name);
}

cmd1.ExecuteNonQuery();
cmd1.Connection = conn;
conn.Close();
SearchExit();
}
}

Answer
cmd1.Connection = conn; 

should be right after you instance it, or even better, pass the conn object in the SqlCommand constructor.