[c#] ExecuteReader: Connection property has not been initialized

ExecuteReader: Connection property has not been initialized.

my coding is

protected void Button2_Click(object sender, EventArgs e)
    {

       SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI");

    SqlDataReader rdr = null;

    try
    {
        // 2. Open the connection
        conn.Open();

        // 3. Pass the connection to a command object
        //SqlCommand cmd = new SqlCommand("select * from Customers", conn);
        SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)
                  values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");

        //
        // 4. Use the connection
        //

        // get query results
        rdr = cmd.ExecuteReader();

        // print the CustomerID of each record
        while (rdr.Read())
        {
            Console.WriteLine(rdr[0]);
        }
    }
    finally
    {
        // close the reader
        if (rdr != null)
        {
            rdr.Close();
        }

        // 5. Close the connection
        if (conn != null)
        {
            conn.Close();
        }
    }
  }
  }

    }

This question is related to c# asp.net sql-server-2005

The answer is


After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... Add

cmd.Connection = conn;

Hope this help


You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:

    // 3. Pass the connection to a command object
    SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
    cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
    cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;

    //
    // 4. Use the connection
    //

By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).


I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.

// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
    try
    {
        conn.Open();

        // initialize command
        using (SqlCommand cmd = conn.CreateCommand())
        {

            // generate query with parameters
            with cmd
            {
                .CommandType = CommandType.Text;
                .CommandText = "insert into time(project,iteration) values(@name, @iteration)";
                .Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
                .Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
                .ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        //throw;
    }
    finally
    {
        if (conn != null && conn.State == ConnectionState.Open)
        {
            conn.Close;
        }
    }
}

All of the answers is true.This is another way. And I like this One

SqlCommand cmd = conn.CreateCommand()

you must notice that strings concat have a sql injection problem. Use the Parameters http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx


you have to assign connection to your command object, like..

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
cmd.Connection = conn; 

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sql-server-2005

Add a row number to result set of a SQL query SQL Server : Transpose rows to columns Select info from table where row has max date How to query for Xml values and attributes from table in SQL Server? How to restore SQL Server 2014 backup in SQL Server 2008 SQL Server 2005 Using CHARINDEX() To split a string Is it necessary to use # for creating temp tables in SQL server? SQL Query to find the last day of the month JDBC connection to MSSQL server in windows authentication mode How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?