petrppe
petrppe

Reputation: 155

Data from SQL reader to datatable - Invalid attempt to call Read when reader is closed

I am keep trying and still don't know how to fix this, keep getting same error. I want to get data from the database to txt file.

    using (conn)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand(command)
    cmd.Connection = (SqlConnection)conn;

    using (cmd)
    {
        SqlDataReader reader = cmd.ExecuteReader();
        using(reader)
        {
             while (reader.Read())
             {
                  dt.Load(reader);
             }
        }

        using (StreamWriter sw = new StreamWriter(txtPath.Text + fileName))
        {
            // write to text file from Datatable dt
        }  }

Upvotes: 0

Views: 59

Answers (2)

paio
paio

Reputation: 167

Try insted your code, something like this:

 DataTable myDataTable = new DataTable();


        using (SqlConnection myConnection = new SqlConnection(yourDBconn)
        {
                yourDBconn.Open();
                using (SqlDataAdapter myAdapter = new SqlDataAdapter(strYourQuery, yourDBconn))
                {
                    myAdapter.Fill(myDataTable);
                }
            }
        }

Upvotes: 2

hungndv
hungndv

Reputation: 2141

Here you are. Tested.

var customers = new List<Tuple<int, string>>(); // the list of ID, Name
using (var con = new SqlConnection("your connection string"))
{
    using(SqlCommand cmd = new SqlCommand("select ID, Name from Customer", con))
    {
        con.Open();       
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                customers.Add(new Tuple<int, string>(
                    (int)reader["ID"], reader["Name"].ToString()));
            }
        }
    }
}
// Store customers to file

Upvotes: 0

Related Questions