0

Hi I am trying to export a SQL Server Query to Excel using C# and I am having trouble.

This is what I have tried so far...

I am not sure that I am using this code correctly and could use assistance.

I Receive the error.

Object reference not set to an instance of an object. (This is not a duplicate of another question)

Update: I now receieve this error after fixing object reference not set to instance of an object:

ExecuteReader: Connection property has not been initialized.

On y1.CommandText

   String connectionString = "";
    connectionString = "REMOVED";
    String Filename = null;
    y1 = new SqlCommand();
    y1.CommandText = @"Select * from products.products";


    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    SqlDataReader dr = y1.ExecuteReader();

    using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
    {
        // Loop through the fields and add headers
        for (int i = 0; i < dr.FieldCount; i++)
        {
            string name = dr.GetName(i);
            if (name.Contains(","))
                name = "\"" + name + "\"";

            fs.Write(name + ",");
        }
        fs.WriteLine();

        // Loop through the rows and output the data
        while (dr.Read())
        {
            for (int i = 0; i < dr.FieldCount; i++)
            {
                string value = dr[i].ToString();
                if (value.Contains(","))
                    value = "\"" + value + "\"";

                fs.Write(value + ",");
            }
            fs.WriteLine();
        }

        fs.Close();
    }
}

Again thank you.

user3768157
  • 41
  • 1
  • 1
  • 4
  • You are trying to set the property (`y1.CommandText = `) before creating the object (`y1 = new `) – D Stanley Jun 23 '14 at 15:55
  • Now i get ExecuteReader: Connection property has not been initialized. on the SqlDataReader dr = y1.ExecuteReader(); – user3768157 Jun 23 '14 at 16:09
  • 1
    You have not set the command. Do some research of using `SQLCommand` and `SqlConnection` rather than just throwing together random code bits. – D Stanley Jun 23 '14 at 16:33

1 Answers1

0

move the line

y1 = new SqlCommand();

above

y1.CommandText = @"Select * from products.products";

you are setting a value for an object before initializing it

Karthik Ganesan
  • 4,142
  • 2
  • 26
  • 42
  • Now i get ExecuteReader: Connection property has not been initialized. on the SqlDataReader dr = y1.ExecuteReader(); – user3768157 Jun 23 '14 at 16:08