-1

I'm trying to export from SQL Server a csv file from a query.

I'm getting the error Object reference not set to an instance of an object on the line

foreach (DataColumn dc in dt.Columns)
{
}

Here is the code i am running for this.

private DataTable GetData()
{
    SqlConnection sqlCon = new SqlConnection("...");
    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.CommandText = "SELECT top 10 * from products.products";
    sqlCmd.Connection = sqlCon;

    sqlCon.Open();
    sqlCmd.ExecuteScalar();
    sqlCon.Close();
    return dt;
}

protected void Button3_Click(object sender, EventArgs e)
{
    DataTable dt = GetData();

    string attachment = "attachment; filename=DataTable.xls";

    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";

    string tab = "";
    foreach (DataColumn dc in dt.Columns)
    {
        Response.Write(tab + dc.ColumnName);
        tab = "\t";
    }

    Response.Write("\n");

    foreach (DataRow dr in dt.Rows)
    {
        tab = "";

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            Response.Write(tab + dr[i].ToString());
            tab = "\t";
        }

        Response.Write("\n");
    }

    Response.End();
}

I'm not sure what to do.

abatishchev
  • 98,240
  • 88
  • 296
  • 433

2 Answers2

3

You have to Fill your DataTable with something:

private DataTable GetData()
{
    DataTable dt = new DataTable();

    SqlConnection sqlCon = new SqlConnection("...");
    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.CommandText = "SELECT top 10 * from products.products";
    sqlCmd.Connection = sqlCon;

    sqlCon.Open();
    dt.Load(sqlCmd.ExecuteReader());
    sqlCon.Close();

    return dt;
}
Fals
  • 6,813
  • 4
  • 23
  • 43
0

Try this:

private DataTable GetData()
{
DataTable dt;
        string connectionString = ConfigurationManager.ConnectionStrings["yourConnection"].ConnectionString;
        //
        // In a using statement, acquire the SqlConnection as a resource.
        //
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            //
            // Open the SqlConnection.
            //
            con.Open();
            //
            // The following code uses an SqlCommand based on the SqlConnection.
            //
            using (SqlCommand command = new SqlCommand("SELECT top 10 * from products.products", con))
            {
                //use SqlDataAdapter to fill the dataTable
                using (SqlDataAdapter a = new SqlDataAdapter(command))
                {
                    dt = new DataTable();
                    a.Fill(dt);
                }

            }
        } 
        return dt;
    }
Audor
  • 46
  • 5